-1

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?

OdieO
  • 6,836
  • 7
  • 56
  • 88

1 Answers1

6

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.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
  • Actually the number before the decimal is for padding with space vs number after the decimal is for padding with zeros. For example with var myInt = Int(13), NSString(format: "%3d", myInt) = " 13" (one leading space), NSString(format: "%.3d", myInt) = "013", NSString(format: "%3.3d", myInt) = "013" and NSString(format: "%5.3d", myInt) = " 013" (two leading spaces) – rockhammer Oct 14 '16 at 21:07
  • @rockhammer What I posted works just fine. What you posted is normally used with floating pointing numbers and the `%f` specifier. – rmaddy Oct 14 '16 at 21:15
  • Understood. It's just that practically every solution people post about converting NSTimeInterval to human readable format uses something like `return NSString(format: "%0.2d:%0.2d:%0.2d.%0.3d",hours,minutes,seconds,ms)` such as this one http://stackoverflow.com/a/28872601/1827488. And I just discovered this decimal convention for `%d` does not work on Android/java as I port code over there. – rockhammer Oct 14 '16 at 23:30