97

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?

Jon Schneider
  • 25,758
  • 23
  • 142
  • 170
ghiboz
  • 7,863
  • 21
  • 85
  • 131

2 Answers2

255

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

Gumbo
  • 643,351
  • 109
  • 780
  • 844
  • To clarify: The "3" can be replaced with any number to have that total count of digits in the displayed value. For example, `%06d` would result in values like `000001`. – Jon Schneider Aug 17 '21 at 13:17
5

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

Alex Zavatone
  • 4,106
  • 36
  • 54
McUsr
  • 1,400
  • 13
  • 10
  • 1
    Note here that the "12" in `@"%012.0F"` refers to the number of total digits, so including the decimal point and anything to the right. – bcattle May 19 '15 at 03:51
  • 1
    To add to bcattle's comment, this also includes anything to the *right* as well. To display -012.34, you'd have to use `@"%07.2f"` – n_b Feb 14 '16 at 21:41