I have the following variable:
NSNumber *consumption = [dict objectForKey:@"con"];
Which returns 42. How can I pad this number to 10 digits on the left, leading with zeros. The output should look as,
0000000042
or if it were 420,
0000000420
Use str. zfill(width) zfill is the best method to pad zeros from the left side as it can also handle a leading '+' or '-' sign. It returns a copy of the string left filled with '0' digits to make a string of length width.
The format() method of String class in Java 5 is the first choice. You just need to add "%03d" to add 3 leading zeros in an Integer. Formatting instruction to String starts with "%" and 0 is the character which is used in padding. By default left padding is used, 3 is the size and d is used to print integers.
Python String zfill() MethodThe zfill() method adds zeros (0) at the beginning of the string, until it reaches the specified length. If the value of the len parameter is less than the length of the string, no filling is done.
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.
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.
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