Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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"
like image 909
aneuryzm Avatar asked Jun 06 '11 14:06

aneuryzm


People also ask

How do you divide a number into 2 digits?

int i = 45; // or anything you want int firstDigit = i / 10; int secondDigit = i % 10; It's quite simple really.

How do you convert a single digit to a double digit in Java?

format() method, which will let you do exactly what you want: String s = String. format("%02d", someNumber);

How do you convert single digit to double digit in react?

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.


2 Answers

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

[NSString stringWithFormat:@"%02d", 1];
like image 169
highlycaffeinated Avatar answered Sep 26 '22 12:09

highlycaffeinated


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.

like image 30
Jeremy W. Sherman Avatar answered Sep 25 '22 12:09

Jeremy W. Sherman