从一位数整数中生成一个两位数的字符串

ane*_*yzm 91 string cocoa objective-c nsstring number-formatting

即使整数小于10,我怎么能在一个字符串中有一个两位数的整数?

[NSString stringWithFormat:@"%d", 1] //should be @"01"
Run Code Online (Sandbox Code Playgroud)

hig*_*ted 301

我相信stringWithFormat说明符是标准的IEEE printf说明符.你有没有尝试过

[NSString stringWithFormat:@"%02d", 1];
Run Code Online (Sandbox Code Playgroud)

  • 喜欢它... 2年在iPhone,现在我知道这...感谢队友 (4认同)

Jer*_*man 25

使用格式字符串%02d.这指定格式化最小字段宽度为2个字符的整数,并将格式化值填充为0以满足该宽度.查看man fprintf格式说明符的所有详细信息.

但是,如果要格式化数字以便向用户显示,那么您应该真正使用它NSNumberFormatter.不同的语言环境对如何格式化数字有着截然不同的期望.