格式字符串,带前导零的整数

我想转换一个整数值到一个字符串与前导零(如果必要的话) ,这样的字符串有3个总字符。例如,5将成为 "005",而 10将成为 "010"

我试过这个代码:

NSString* strName = [NSString stringWithFormat:@"img_00%d.jpg", i];

这只是部分工作,但是如果 i的值为 10,那么结果就是 img_0010.jpg,而不是 img_010.jpg

有什么办法能让我做我想做的事吗?

46629 次浏览

Use the format string "img_%03d.jpg" to get decimal numbers with three digits and leading zeros.

For posterity: this works with decimal numbers.

NSString *nmbrStr = @"0033620340000" ;
NSDecimalNumber *theNum = [[NSDecimalNumber decimalNumberWithString:nmbrStr]decimalNumberByAdding: [NSDecimalNumber one]] ;
NSString *fmtStr = [NSString stringWithFormat:@"%012.0F",[theNum doubleValue]] ;

Though this information is hard to find, it is actually documented here in the second paragraph under Formatting Basics. Look for the % character.

https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/Strings/Articles/FormatStrings.html