开发者

Format string, integer with leading zeros

开发者 https://www.devze.com 2023-01-02 06:12 出处:网络
I want to convert an integer value to a string with leading zeroes (if necessary) such that the string has 3 total characters. For example, 5 would become "005", and 10 would become "01

I want to convert an integer value to a string with leading zeroes (if necessary) such that the string has 3 total characters. For example, 5 would become "005", and 10 would become "010开发者_JS百科".

I've tried this code:

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

This partially works, but if i has the value of 10, for example, the result is img_0010.jpg, not img_010.jpg.

Is there a way to do what I want?


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

0

精彩评论

暂无评论...
验证码 换一张
取 消