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

前端 未结 7 1445
鱼传尺愫
鱼传尺愫 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: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.

提交回复
热议问题