Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 580
George Johnston Avatar asked Jun 17 '11 19:06

George Johnston


People also ask

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

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.

How do I add a 0 to an integer?

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.

How do you fill a string with zeros?

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.


2 Answers

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.

like image 97
taskinoor Avatar answered Sep 18 '22 13:09

taskinoor


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.

like image 36
Deepak Danduprolu Avatar answered Sep 17 '22 13:09

Deepak Danduprolu