How can I pad an integer on the left with zeros?

前端 未结 7 1358
鱼传尺愫
鱼传尺愫 2020-12-09 07:18

I have the following variable:

NSNumber *consumption = [dict objectForKey:@\"con\"];

Which returns 42. How can I pad this number to 10 dig

相关标签:
7条回答
  • 2020-12-09 08:09

    E.g. Fill the rest with zeros, 5 digits:

    NSInteger someValue = 10;
    [NSString stringWithFormat:@"%05ld", someValue];
    

    Equivalent of .02f for float number when you need only 2 digits after the dot.

    So there you have 0 = fill with zeros, 5 = the number of digits and type.

    0 讨论(0)
  • 2020-12-09 08:10

    You can't in the NSNumber itself. If you're creating a string from the number or using NSLog(), simply use the appropriate format, e.g.

    NSLog(@"%010d", [consumption intValue]);
    
    0 讨论(0)
  • 2020-12-09 08:12

    The Objective-C way,

    NSNumberFormatter * numberFormatter = [[[NSNumberFormatter alloc] init] autorelease];
    [numberFormatter setPaddingPosition:NSNumberFormatterPadBeforePrefix];
    [numberFormatter setPaddingCharacter:@"0"];
    [numberFormatter setMinimumIntegerDigits:10];
    
    NSNumber * number = [NSNumber numberWithInt:42];
    
    NSString * theString = [numberFormatter stringFromNumber:number];
    
    NSLog(@"%@", theString);
    

    The C way is faster though.

    0 讨论(0)
  • 2020-12-09 08:13

    Solution for Swift 3

    let x = 1078.1243
    let numFormatter = NumberFormatter()
    numFormatter.minimumFractionDigits = 1 // for float
    numFormatter.maximumFractionDigits = 1 // for float
    numFormatter.minimumIntegerDigits = 10 // how many digits do want before decimal
    numFormatter.paddingPosition = .beforePrefix
    numFormatter.paddingCharacter = "0"
    
    let s = numFormatter.string(from: NSNumber(floatLiteral: x))!
    

    OUTPUT

    "0000001078.1"

    0 讨论(0)
  • 2020-12-09 08:17

    You can do pretty much any number formatting you would ever want with NSNumberFormatter. In this case I think you would want to use the setFormatWidth: and setPaddingCharacter: functions.

    0 讨论(0)
  • 2020-12-09 08:18
    NSString *paddedStr = [NSString stringWithFormat:@"%010d", 42];
    

    EDIT: It's C style formatting. %nd means the width is at least n. So if the integer is 2 digit long, then you will have length 3 string (when %3d is used). By default the left empty spaces are filled by space. %0nd (0 between % and n) means 0 is used for padding instead of space. Here n is the total length. If the integer is less than n digits then left padding is used.

    0 讨论(0)
提交回复
热议问题