NSString formatting

3.4k Views Asked by At

I'm changing some pre-written code and a video timeLabel is formatted like so:

return [NSString stringWithFormat:@"%2d:%0.2d", minutes, seconds];

What's happening is the if the minutes is a single digit, it's returning a space before it, eg 4:49 has a space before the 4. How do I format so that there are 2 characters in the string if the minutes arguments is 2 digits, but just 1 character if minutes is 1 digit?

1

There are 1 best solutions below

3
rmaddy On BEST ANSWER

You want the following:

return [NSString stringWithFormat:@"%d:%02d", minutes, seconds];

Simply using %d will show the number in however many digits it needs. And the seconds shouldn't have a decimal. The %02d says to show with at least two digits and left fill with leading zeros to ensure there are two digits if needed.