Today, I wanted to display a time-value of 9 minutes and 3 seconds like this: 09:03
Thus, I typed this snippet into my Objective-C code:
labelTimer.text = [NSString stringWithFormat:@"%2d:%2d", minutes, seconds ];
[/code]
This did not yield the result I wanted. The numbers were padded with spaces, not zeros. Sadly, Apple left out the options for the different format specifiers like f, d, @ … completely. You have to rely on old C skills in order to know how to pad with zeros or format decimal numbers the way you want. As a side-note, if you have a float and want to format it with 2 decimals, use %.2f. In order to pad zeros, you have to use %02d in this case, which leads to the following snippet in Objective-C code:
labelTimer.text = [NSString stringWithFormat:@"%02d:%02d", minutes, seconds ];

No comments
Comments feed for this article
Trackback link
http://www.flickdotnet.de/index.php/2010/04/nsstring-using-stringwithformat-and-left-pad-integers-with-zeros/trackback/