Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create int values with '0' prefix

Tags:

objective-c

I am using Objective-C and trying to create int values that are between 1-99 and if less than 10 I would like them to show as 01, 02, 03, 04, 05, etc. Can anyone tell me how to do that?

Thanks!

like image 752
Jake Sankey Avatar asked Dec 12 '22 12:12

Jake Sankey


2 Answers

Besides PengOne's answer, you could also use a format string.

NSLog(@"%02d", 3);

says 'print the following int with at least 2 digits' and will add the leading 0 if it only has one. It will print

03

Or if you want an NSString,

NSString *tst = [NSString stringWithFormat:@"%02d", 5];
like image 75
Rob Lourens Avatar answered Dec 15 '22 01:12

Rob Lourens


You can simply print i with a 0 when it's less than 10 using

NSLog(@"%@%d", (i<10 ? @"0" : @""), i );

Alternately, if you want a string,

NSString *paddedNum = [NSString stringWithFormat:@"%@%d",(i<10 ? @"0" : @""),i];
like image 31
PengOne Avatar answered Dec 15 '22 02:12

PengOne