Make a two-digit string from a single-digit integer

Objective CStringCocoaNsstringNumber Formatting

Objective C Problem Overview


How can I have a two-digit integer in a a string, even if the integer is less than 10?

[NSString stringWithFormat:@"%d", 1] //should be @"01"

Objective C Solutions


Solution 1 - Objective C

I believe that the stringWithFormat specifiers are the standard IEEE printf specifiers. Have you tried

[NSString stringWithFormat:@"%02d", 1];

Solution 2 - Objective C

Use the format string %02d. This specifies to format an integer with a minimum field-width of 2 characters and to pad the formatted values with 0 to meet that width. See man fprintf for all the gory details of format specifiers.

If you are formatting numbers for presentation to the user, though, you should really be using NSNumberFormatter. Different locales have wildly different expectations about how numbers should be formatted.

Solution 3 - Objective C

[NSString stringWithFormat:@"%00.02d", intValue]

This help me to convert 1 to 01.

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
QuestionaneuryzmView Question on Stackoverflow
Solution 1 - Objective ChighlycaffeinatedView Answer on Stackoverflow
Solution 2 - Objective CJeremy W. ShermanView Answer on Stackoverflow
Solution 3 - Objective Cuser2357514View Answer on Stackoverflow