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
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.
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.
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.
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.
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];
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