Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Limit a double to two decimal places [duplicate]

How do I achieve the following conversion from double to a string:

1.4324 => "1.43"
9.4000 => "9.4"
43.000 => "43"

i.e. I want to round to to decimal places but dont want any trailing zeros, ie i dont want

9.4 => "9.40" (wrong)
43.000 => "43.00" (wrong)

So this code which I have now doesn't work as it displays excess zeros:

[NSString stringWithFormat: @"%.2f", total]
like image 834
Jay Avatar asked Jul 11 '09 10:07

Jay


People also ask

How do you limit a double to two decimal places?

DecimalFormat(“0.00”) We can use DecimalFormat("0.00") to ensure the number always round to 2 decimal places.

How do you only get to two decimal places?

If we want to round 4.732 to 2 decimal places, it will either round to 4.73 or 4.74. 4.732 rounded to 2 decimal places would be 4.73 (because it is the nearest number to 2 decimal places). 4.737 rounded to 2 decimal places would be 4.74 (because it would be closer to 4.74).

How do you round a double in Java?

round() Math. round() accepts a double value and converts it into the nearest long value by adding 0.5 to the value and truncating its decimal points. The long value can then be converted to an int using typecasting.


1 Answers

You made simple mistake. This will work:

[NSString stringWithFormat: @"%.2lf", total]
like image 94
Siva Krishna Avatar answered Sep 19 '22 15:09

Siva Krishna