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?

2 Answers 2

255

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

Sign up to request clarification or add additional context in comments.

1 Comment

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.
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

2 Comments

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.
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"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.