Objective-C how to print out leading 0 for a float?

倾然丶 夕夏残阳落幕 提交于 2019-11-30 02:10:15

问题


How do you print out leading zeros for a float using the NSString type?

Input: 3.14
Desired output: 03.1

Using format @"%02.1f"
Output: 3.1

回答1:


You want @"04.1f". The 4 is the total width.

As you can see from the documentation, the format strings conform to the IEEE printf specification.

The format string you've specified breaks down as follows:

0 -- Pad with zeros.
2 -- The entire resulting formatted value will have a minimum width of 2.
.1 -- Precision of 1 digit following the decimal point.




回答2:


For some reason you can't set the pre-decimal width on float numbers (maybe it's a bug you should report). This means you will have to split the number at the decimal format each the way you want and then merge them into one string (@"%i.%i", preDec, postDec).



来源:https://stackoverflow.com/questions/3543896/objective-c-how-to-print-out-leading-0-for-a-float

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