I want to convert an integer value to a string with leading zeroes (if necessary) such that the string has 3 total characters. For example, 5
would become "005"
, and 10
would become "010"
.
I've tried this code:
NSString* strName = [NSString stringWithFormat:@"img_00%d.jpg", i];
This partially works, but if i
has the value of 10
, for example, the result is img_0010.jpg
, not img_010.jpg
.
Is there a way to do what I want?
You can add leading zeros to an integer by using the "D" standard numeric format string with a precision specifier. You can add leading zeros to both integer and floating-point numbers by using a custom numeric format string. This article shows how to use both methods to pad a number with leading zeros.
For padding a string with leading zeros, we use the zfill() method, which adds 0's at the starting point of the string to extend the size of the string to the preferred size. In short, we use the left padding method, which takes the string size as an argument and displays the string with the padded output.
format("%05d", yournumber); for zero-padding with a length of 5.
Use the format string "img_%03d.jpg"
to get decimal numbers with three digits and leading zeros.
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