在我的應用程序中,我有一個音樂播放器,播放音樂的時間長度爲0:30秒。格式化float值以獲取小數點前的數字
但是,在UILabel中,我正在顯示進度,並且因爲它是浮點數,所以標籤顯示的是14.765。
我將不勝感激,如果你能告訴我,我怎麼能拿標籤顯示
0:14,而不是14.765。
此外,我將不勝感激,如果你能告訴我怎麼可以顯示0:04,如果進展是4秒。
在我的應用程序中,我有一個音樂播放器,播放音樂的時間長度爲0:30秒。格式化float值以獲取小數點前的數字
但是,在UILabel中,我正在顯示進度,並且因爲它是浮點數,所以標籤顯示的是14.765。
我將不勝感激,如果你能告訴我,我怎麼能拿標籤顯示
0:14,而不是14.765。
此外,我將不勝感激,如果你能告訴我怎麼可以顯示0:04,如果進展是4秒。
這正常工作:
float time = 14.765;
int mins = time/60;
int secs = time-(mins*60);
NSString * display = [NSString stringWithFormat:@"%d:%02d",mins,secs];
結果:
14.765 => 0:14
30.000 => 0:30
59.765 => 0:59
105.999 => 1:45
編輯
此外, '一個班輪':
float time = 14.765;
NSString * display = [NSString stringWithFormat:@"%d:%02d",(int)time/60,(int)time%60];
//%60 remove the minutes and int removes the floatingpoints
int seconds = (int)(14.765)%60;
// calc minutes
int minutes = (int)(14.765/60);
// validate if seconds have 2 digits
NSString time = [NSString stringWithFormat:@"%i:%02i",minutes,seconds];
,應該工作。不能測試它我在Win目前
您首先需要將您的float
轉換爲一個整數,如您所願舍入。然後,您可以使用整數除法,/
,而其餘%
操作提取分鐘和秒,併產生一個字符串:
float elapsedTime = 14.765;
int wholeSeconds = round(elapsedTime); // or ceil (round up) or floor (round down/truncate)
NSString *time = [NSString stringWithFormat:@"%02d:%02d", wholeSeconds/60, wholeSeconds%60];
的%02d
是一個2位數的格式規範,補零整數 - 看在文檔中提供printf
以獲取完整詳細信息。
謝謝安妮!非常感謝! – 2011-04-14 21:10:50