简体   繁体   中英

Format a float to display in a string with two digits?

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

So I have this string and a bunch of floats. For example, say seconds = 6.54. It will display as that. I want it to display as 06.54. Is there anyway to do that? Any help with be greatly appreciated.

Assuming you want 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 float the number before the point (05) determines the minimum total characters in the entire string, not just the bit before the point.

One way to approach is to have a separate NSString having content 0 and append it with timerend . There might even be other better solutions.

NSString *startTag = @"0";
// Your string variable. i.e., timerend

NSString *newTime = [startTag stringByAppendingString:timerend];

However, you need to append only when the hour is less than 10.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM