How to pad the integer withe preceeding 0?

£可爱£侵袭症+ 提交于 2019-12-11 13:38:13

问题


I am having an integer value like 6 or 65 . If the value is single digit I want to display it like 06 and if it is 65 then as it is ( 65 only ) . I have searched into the NSNumberFormatter class of iphone but not getting what to do exactly . Can any one help me in this ?

Thanks in advance !!


回答1:


Use %02d format specifier, e.g.

NSLog(@"%02d", number);

That will output integer number with at least 2 characters length and output will be padded with leading zeroes if required




回答2:


For using the format specifiers as Vladimir suggested, you can also use the stringWithFormat convenience method on NSString to generate a string from a numeric value in the desired format.




回答3:


Here is another option, although I think Vladimir's is prob the most clean. :)

NSLog(@"%@%d", number<10?@"0":@"", number);


来源:https://stackoverflow.com/questions/5563825/how-to-pad-the-integer-withe-preceeding-0

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