Make a float only show two decimal places

ron picture ron · Feb 18, 2009 · Viewed 270.7k times · Source

I have the value 25.00 in a float, but when I print it on screen it is 25.0000000.
How can I display the value with only two decimal places?

Answer

Andrew Grant picture Andrew Grant · Feb 18, 2009

It is not a matter of how the number is stored, it is a matter of how you are displaying it. When converting it to a string you must round to the desired precision, which in your case is two decimal places.

E.g.:

NSString* formattedNumber = [NSString stringWithFormat:@"%.02f", myFloat];

%.02f tells the formatter that you will be formatting a float (%f) and, that should be rounded to two places, and should be padded with 0s.

E.g.:

%f = 25.000000
%.f = 25
%.02f = 25.00