2014-02-22 47 views
0
// 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格式化NSTimeInterval

我怎麼會輸出00:00.00,並將它增加一個第二的每第100,而不是第二個10?

+0

使所述第一和第三格式說明符像你的第二個。 '%02u'。 – rmaddy

+0

而這將是百分之一秒,而不是毫秒。毫秒需要三位小數。多個乘以100,而不是10. – rmaddy

+0

對於毫秒,您需要將小數乘以1000.並使用'%03u'。 –

回答

1
returnTimeString = [NSString stringWithFormat:@"%02u:%05.2f", 
    (int)(elapsed/60), fmod(elapsed, 60)]; 
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] 
+0

這似乎是工作的,除了最後一個數字(百分之一)似乎只在0.7之間搖擺不定,與原生iOS Stopwatch應用相比,它在0-9之間擺動,儘管速度非常快,不知道爲什麼會這樣? – Apollo

+0

也許秒錶應用以更高的頻率刷新,或作弊和有一個固定的動畫爲最後的數字,而不是顯示真正的值,直到停止... – Arkku