user5334106
user5334106

Reputation:

Rounding "string number" with decimal comma

What is the best way to round a string number with a decimal comma and keep it as a string?

Do I have to convert the string to a double, then round it to the nearest integer and then convert it back to a string?

For example, "21,55" should be rounded to "22".

Upvotes: 0

Views: 256

Answers (2)

Atri
Atri

Reputation: 5831

You can use the following:

String s = "21,55";
s = s.replace(',', '.');
s = Long.toString(Math.round(Double.parseDouble(s)));

First replace the , with a .

Then convert the String to Double and then round the value. Since Math.round(Double) will return a long, you need to convert it to String.

Upvotes: 1

Ankit Deshpande
Ankit Deshpande

Reputation: 3604

Math.floor rounds it to lower integer value and Math.ceil rounds it up to higer integer value use math.round in your case

Long.toString(Math.round(Double.parseDouble(strNum)));

Upvotes: 0

Related Questions