2

I want to keep the zero at the beginning of my NSInteger, but when i NSLog it, the zero is removed.

NSInteger myInteger = 05;
NSLog("%d", myInteger);

log: 5

I get 5 instead of 05. How can i keep the 0 at the beginning of the integer?

Aleksander Azizi
  • 9,829
  • 9
  • 59
  • 87

4 Answers4

16

NSInteger doesn't do "leading" zeros. You're thinking about a number formatting thing.

If you just want to print out leading zeros via "NSLog", try something like:

NSLog( "%02d", myInteger);

Which instructs NSLog to have two digits and if it doesn't reach two digits, do a leading zero.

Take a look at the printf format specifiers (which NSLog tries to conform to) and you'll see how leading zeros are added there.

Michael Dautermann
  • 88,797
  • 17
  • 166
  • 215
2

I am not sure, but I think it is a question of how you write your "%d" flag. So you cas use NSLog(@"%03d", var);.

It will print 005.

lthms
  • 509
  • 3
  • 10
1

This is how it works for strings:

INT

String(format:"%05.2f", 5.0) will output: 05.00

DOUBLE

String(format:"%02d", 5) will output: 05

mothy
  • 147
  • 2
  • 8
0

If you need it just for logging try it like this

NSLog(@"0%d" , 5) ;

or if you need to print it on the screen convert to string with format :

NSString *result = [[NSString alloc]initWithFormat:@"0%d" , yourInteger] ;
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
MoSaber
  • 21
  • 3