How to print formatted float in obj-c?

谁说我不能喝 提交于 2019-12-07 06:45:05

问题


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 (NSStrings) 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!