Format a float to display in a two-digit string?

NSString *timerend = [[NSString alloc] initWithFormat:@"%.0f:%.0f:%02d", hours, minutes, seconds]; 

So, I have this line and a bunch of floats. For example, say seconds = 6.54. It will be displayed as such. I want it to display as 06.54. Is there any way to do this? Any help greatly appreciated.

+7
source share
2 answers

Assuming you need the format "XX: XX: XX.XX", you can use the following code:

  NSString *timerend = [[NSString alloc] initWithFormat:@"%02.0f:%02.0f:%05.2f", hours, minutes, seconds]; 

When formatting floats a number before the dot (05) defines the minimum common characters in the entire string, not just the bit to the dot.

+15
source

One approach is to have a separate NSString that has content 0 and add it using timerend . There may be other better solutions.

 NSString *startTag = @"0"; // Your string variable. ie, timerend NSString *newTime = [startTag stringByAppendingString:timerend]; 

However, you only need to add if the hour is less than 10.

0
source

All Articles