问题
How to print a float
in Objective-C as, for example, 3.45
instead of 3.45555555555
?
回答1:
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"
.
回答2:
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".
来源:https://stackoverflow.com/questions/9540301/how-to-print-formatted-float-in-obj-c