从单位数字整数生成两位数字字符串

如何在一个字符串中有一个两位数的整数,即使这个整数小于10?

[NSString stringWithFormat:@"%d", 1] //should be @"01"
45935 次浏览

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

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

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.

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

This help me to convert 1 to 01.