Format string, integer with leading zeros
46,300
Solution 1
Use the format string "img_%03d.jpg"
to get decimal numbers with three digits and leading zeros.
Solution 2
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.
![ghiboz](https://i.stack.imgur.com/eohqx.jpg?s=256&g=1)
Author by
ghiboz
c# programmer for work, php, objective-c, c++ programmer for passion
Updated on July 08, 2022Comments
-
ghiboz almost 2 years
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"
, and10
would become"010"
.I've tried this code:
NSString* strName = [NSString stringWithFormat:@"img_00%d.jpg", i];
This partially works, but if
i
has the value of10
, for example, the result isimg_0010.jpg
, notimg_010.jpg
.Is there a way to do what I want?