Padding a number in NSString
Solution 1
Try this:
NSLog(@"%04d", 45);
NSLog(@"%04d", 9);
If it works, then you can get padded number with
NSString *paddedNumber = [NSString stringWithFormat:@"%04d", 45];
NSString *otherPaddedNumber = [NSString stringWithFormat:@"%04d", 9];
Update
If you want to have arbitrary number you'd have to create a format for your format:
// create "%04d" format string
NSString *paddingFormat = [NSString stringWithFormat:@"%%0%dd", 4];
// use it for padding numbers
NSString *paddedNumber = [NSString stringWithFormat:paddingFormat, 45];
NSString *otherPaddedNumber = [NSString stringWithFormat:paddingFormat, 9];
Update 2
Please see @Ibmurai's comment on how to properly pad a number with NSLog.
Solution 2
Excuse me for answering this question with an already accepted answer, but the answer (in the update) is not the best solution.
If you want to have an arbitrary number you don't have to create a format for your format, as IEEE printf supports this. Instead do:
NSString *paddedNumber = [NSString stringWithFormat:@"%0*d", 4, 45];
NSString *otherPaddedNumber = [NSString stringWithFormat:@"%0*d", 4, 9];
While the other solution works, it is less effective and elegant.
From the IEEE printf specification:
A field width, or precision, or both, may be indicated by an asterisk ( '*' ). In this case an argument of type int supplies the field width or precision.
Solution 3
Swift version as Int extension (one might wanna come up with a better name for that method):
extension Int
{
func zeroPaddedStringValueForFieldWidth(fieldWidth: Int) -> String
{
return String(format: "%0*d", fieldWidth, self)
}
}
Examples:
print( 45.zeroPaddedStringValueForFieldWidth(4) ) // prints "0045"
print( 9.zeroPaddedStringValueForFieldWidth(4) ) // prints "0009"
Related videos on Youtube
RungaDeMungoezz
Updated on July 06, 2022Comments
-
RungaDeMungoezz almost 2 years
I have an int, for example say 45. I want to get NSString from this int padded with 4 zeroes. So the result would be :
@"0045"
. Similar, if the int is 9, I want to get:@"0009"
.I know I can count the number of digits, then subtract it from how many zeroes i want padded, and prepend that number to the string, but is there a more elegant way? Thanks.
-
RungaDeMungoezz almost 13 yearsThanks for the quick reply. This works perfectly, but how can I specify an arbitrary number? I tried: NSLog(@"%0%id",4, 45); but this doesn't work. Thanks again.
-
RungaDeMungoezz almost 13 yearsThanks dude! you saved my life.
-
Ibmurai over 11 yearsIt's silly to create a format for your format. Simply use [NSString stringWithFormat:@"%0*d", 4, 45]. The *, the length to pad, refers to an argument, too... So 4 "replaces" the star.
-
Eimantas over 11 years@Ibmurai Now that you showed the shortest answer - it really is silly. My printf-fu is weak .)