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"
int i = 45; // or anything you want int firstDigit = i / 10; int secondDigit = i % 10; It's quite simple really.
format() method, which will let you do exactly what you want: String s = String. format("%02d", someNumber);
The padStart() method is used on this string with the length parameter given as 2 and the string to be replaced with, given the character '0'. This will format any single digit number to 2 digits by prepending a '0' and leave 2 digit numbers as is.
I believe that the stringWithFormat specifiers are the standard IEEE printf specifiers. Have you tried
[NSString stringWithFormat:@"%02d", 1];
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With