How to print a float
in Objective-C as, for example, 3.45
instead of 3.45555555555
?

- 32,014
- 33
- 141
- 226
-
possible duplicate of [how to set the float value to two decimal number in objective C](http://stackoverflow.com/questions/560517/how-to-set-the-float-value-to-two-decimal-number-in-objective-c) – jscs Mar 02 '12 at 21:08
2 Answers
Try formatting the float like this:
NSLog(@"%.2f", myFloat);
The %
sign means this will be replaced by the corresponding argument following (myFloat
). The .2
means 2 decimal places, and f
means a float
datatype.
Take a look here for more detail.
Objective-C's NSLog
is very similar to C's printf
, with the main exceptions being that you must use an Objective-C string literal (@"…"
) and you should use %@
for Objective-C strings (NSString
s) rather than %s
, which is for "Plain C strings"
.
-
@Austin - What do you mean by dynamic? Can you edit your post and explain that? – sch Mar 02 '12 at 21:15
-
Depends on how you're printing it. If you want to show it in a GUI (which is probably the common case for Cocoa and Cocoa Touch apps), use an NSNumberFormatter and set it to have two decimal places. If you're printing it through NSLog() or printf(), you'd use a format specifier along the lines of "%.2f".

- 234,037
- 30
- 302
- 389