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]
DecimalFormat(“0.00”) We can use DecimalFormat("0.00") to ensure the number always round to 2 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).
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.
You made simple mistake. This will work:
[NSString stringWithFormat: @"%.2lf", total]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With