Format string, integer with leading zeros

Objective CStringFormatting

Objective C Problem Overview


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?

Objective C Solutions


Solution 1 - Objective C

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

Solution 2 - Objective C

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionghibozView Question on Stackoverflow
Solution 1 - Objective CGumboView Answer on Stackoverflow
Solution 2 - Objective CMcUsrView Answer on Stackoverflow