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
7880开发者_运维知识库1
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.
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"
)
NSLog(@"%05i", rdmNr);
The 5
means that 5 characters should be printed, the 0
means that it should be padded with zeros to the left.
NSLog accepts the same arguments as printf
(see here) in addition %@
prints an NSString, more info here.
You can also find some common specifiers at Placeholders on Wikipedia
精彩评论