Make a two-digit string from a single-digit integer

 ̄綄美尐妖づ 提交于 2019-11-27 05:02:30

问题


How can I have a two-digit integer in a a string, even if the integer is less than 10?

[NSString stringWithFormat:@"%d", 1] //should be @"01"

回答1:


I believe that the stringWithFormat specifiers are the standard IEEE printf specifiers. Have you tried

[NSString stringWithFormat:@"%02d", 1];



回答2:


Use the format string %02d. This specifies to format an integer with a minimum field-width of 2 characters and to pad the formatted values with 0 to meet that width. See man fprintf for all the gory details of format specifiers.

If you are formatting numbers for presentation to the user, though, you should really be using NSNumberFormatter. Different locales have wildly different expectations about how numbers should be formatted.




回答3:


[NSString stringWithFormat:@"%00.02d", intValue]

This help me to convert 1 to 01.



来源:https://stackoverflow.com/questions/6253666/make-a-two-digit-string-from-a-single-digit-integer

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