Take the 2-minute tour ×

I am trying to generate a numerical string by padding the number with zeroes to the left.

0 would become 00000 1 would become 00001 10 would become 00010

I want to create five character NSString by padding the number with zeroes.

I read this Create NSString by repeating another string a given number of times but the output is an NSMutableString.

How can I implement this algorithm with the output as an NSString?

Best regards.

share|improve this question

2 Answers 2

up vote 9 down vote accepted

You can accomplish this by calling

[NSString stringWithFormat:@"%05d", [theNumber intValue]];

where theNumber is the NSString containing the number you want to format.

For further reading, you may want to look at Apple's string formatting guide or the Wikipedia entry for printf.

share|improve this answer
it's @"%05d" not a "%5d". –  hoha Mar 18 '11 at 23:31
D'oh! Thanks, you'd think I would remember something like that by now. –  jonmorgan Mar 18 '11 at 23:33
I have nsstring not an integer that @"10" or @"1" –  Ali Mar 18 '11 at 23:36
0 is still missing before 5d - this expression is not of much use to OP without it ;). Anyway he want to make it from string, not a number. –  hoha Mar 18 '11 at 23:39
@Ali, I've edited it to work with an NSString as opposed to an int. @hoha, thanks again. –  jonmorgan Mar 18 '11 at 23:48

One quick & simple way to do it:

unsigned int num = 10;  // example value
NSString *immutable = [NSString stringWithFormat:@"%.5u", num];

If you actually really want to use the long-winded approach from the example you read, you can send a “copy” message to a mutable string to get an immutable copy. This holds for all mutable types.

share|improve this answer

Your Answer


