格式化NSTimeInterval

时间:2014-02-22 01:19:49

标签: ios objective-c

// calculate elapsed time
NSTimeInterval elapsed = currentTime - startTime;

int mins = (int) (elapsed / 60.0);
elapsed -= mins * 60;
int secs = (int) (elapsed);
elapsed -= secs;
int fraction = elapsed * 10.0;

// update time label using format 0:00:0
returnTimeString = [NSString stringWithFormat:@"%u:%02u.%u",mins,secs,fraction];

目前输出0:00.0

我如何输出00:00.00并让它每百分之一秒而不是十分之一秒增加?

2 个答案:

答案 0 :(得分:1)

returnTimeString = [NSString stringWithFormat:@"%02u:%05.2f",
    (int)(elapsed/60), fmod(elapsed, 60)];

答案 1 :(得分:0)

您可以在格式说明符中使用0n将显示的数字的长度零填充到n位数(其中n是正整数),例如,

unsigned int seconds = elapsed;
unsigned int hundredths = (elapsed - seconds) * 100.0;
[NSString stringWithFormat:@"%02u:%02u.%02u", (seconds/60), (seconds%60), hundredths]