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.

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

Share:
46,300
ghiboz
Author by

ghiboz

c# programmer for work, php, objective-c, c++ programmer for passion

Updated on July 08, 2022

Comments

  • ghiboz
    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", and 10 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 of 10, for example, the result is img_0010.jpg, not img_010.jpg.

    Is there a way to do what I want?