Search code examples
iphoneobjective-cnsstringnslog

printing int with specified nr of digits


I am trying to print out a 5 digit number as follows:

int rdmNr = arc4random()%100000;
NSLog(@"%i",rdmNr);

I always would like to have 5 digit numbers. Example outputs should be:

00001
10544
00555
78801

But with the previous code I would also get 1 or 555 without 0s. I also tried %5i, but the I just get more white spaces.


Solution

  • try

    NSLog(@"%05i",rdmNr);
    

    In general, you can specify 2 types of padding for NSLog - filling the required extra characters with spaces (@"%5i") or with leading zeros (@"%05i")