Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Append zero to number if less than 10? [duplicate]

I have an int representing lives.

NSString* lifeString = [NSString stringWithFormat:@"%d",lives];

However it outputs:

1
2
3
..
10
...

I need:

    01
    02
    03
    ..
    10
    ...

I know I can do this with an if statement, but I am wondering if NSString might have a clever way to do it.

Thanks

like image 672
jmasterx Avatar asked Nov 17 '13 00:11

jmasterx


People also ask

How do you add leading zeros when a number is less than 10 in Java?

To add leading zeros to a number, you need to format the output. Let's say we need to add 4 leading zeros to the following number with 3 digits. int val = 290; For adding 4 leading zeros above, we will use %07d i.e. 4+3 = 7.

How do you add leading zeros when a number is less than 10 in PHP?

php $num = 4; $num_padded = sprintf("%02d", $num); echo $num_padded; // returns 04 ?> It will only add the zero if it's less than the required number of characters.

How do you add leading zeros to numbers or text with uneven lengths JS?

Use the String() object to convert the number to a string. Call the padStart() method to add zeros to the start of the string. The padStart method will return a new, padded with leading zeros string.

How do you keep leading zeros in JavaScript?

String(num). padStart(5, "0"); Here, num is the number whose leading zeroes need to be preserved. 5 is the number's target length, and the "0" needs to be padded at the front using the padStart() method.


1 Answers

Use %02d as your format code to require a particular length (i.e. 2), and the left padding value of zero:

NSString* lifeString = [NSString stringWithFormat:@"%02d",lives];
like image 106
Sergey Kalinichenko Avatar answered Oct 01 '22 22:10

Sergey Kalinichenko