Reputation: 51
Could someone tell me how I can round a double & then remove the numbers after the decimal places - & then convert this number to a String please?
e.g. start with a double value 55.6666666666667 - round it up to a double value of 56.0000000000 -
or start with 55.333333333333 - round down to a double value of 55.0000000000 -
& then remove the decimal point and trailing zeros - convert to String.
Thanks.
Upvotes: -1
Views: 5253
Reputation: 31699
Assuming that you don't actually want to save the rounded value, but just want to see it as a string, this should do everything you want, where x
is the double
:
String s = String.format("%.0f", x);
Upvotes: 0
Reputation: 1341
Use the Math.round()
function. You can cast it to an int
to eliminate the decimal places, or you can use Math.floor()
or Math.ceil()
to round it down or up before casting.
Upvotes: 1
Reputation: 1487
The best way to round a value to the nearest integer is:
int x = (int)Math.round(55.6666666666667);
x
will be 56. You can also use Math.ceil()
and Math.floor()
to round up or down respectively. Finally to make x
a string use String.valueOf()
. Like this:
String xString = String.valueOf(x);
If you wanted to do it all on one line:
String xString = String.valueOf(Math.round(55.6666666666667));
You can read more about the Math
class here and the String class here.
Upvotes: 5