Objective-c – Limit a double to two decimal places

c++cocoaformattingobjective-c

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]

Best Solution

You made simple mistake. This will work:

[NSString stringWithFormat: @"%.2lf", total]