2011-04-14 67 views
0

在我的應用程序中,我有一個音樂播放器,播放音樂的時間長度爲0:30秒。格式化float值以獲取小數點前的數字

但是,在UILabel中,我正在顯示進度,並且因爲它是浮點數,所以標籤顯示的是14.765。

我將不勝感激,如果你能告訴我,我怎麼能拿標籤顯示

0:14,而不是14.765。

此外,我將不勝感激,如果你能告訴我怎麼可以顯示0:04,如果進展是4秒。

回答

3

這正常工作:

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]; 
+0

謝謝安妮!非常感謝! – 2011-04-14 21:10:50

1
//%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目前

+1

爲什麼不使用零填充格式字符串:'「%i:%02i」'?它會消除if語句。 – 2011-04-14 20:31:20

+0

%(餘數)在float操作數上無效,必須先轉換爲整數 – CRD 2011-04-14 20:47:00

+0

@Black Frog:不知道該選項,但非常感謝! @CRD:謝謝,這是正確的 – Seega 2011-04-15 10:25:19

2

您首先需要將您的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以獲取完整詳細信息。

相關問題