How to pad the integer withe preceeding 0?

2019-08-01 10:48发布

问题:

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);