Padding a number in NSString

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.


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.


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.


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"
链接地址: http://www.djcxy.com/p/85226.html

上一篇: 检查一个NSString是否仅仅由空格组成

下一篇: 在NSString中填充一个数字