2014-10-28 29 views
0

因此,我正在製作一個應用程序,您在此輸入一個時間(1:32.40),然後將此時間除以數字(50)。到目前爲止,我把所有東西都做成了浮點數,但這顯然是不正確的。我如何讓用戶像普通一樣輸入時間,然後將其轉換爲易於整除的浮點數? 我的計算功能目前看起來像這樣如何通過浮點數劃分輸入的時間

func calculation() -> Bool{ 
     raceDistance = txtRaceDistance.text 
     practiceDistance = txtPracticeDistance.text 
     goalTime = txtGoalTime.text 

     var fGoalTime = (goalTime as NSString).floatValue 
     var fRaceDistance = (raceDistance as NSString).floatValue 
     var fPracticeDistance = (practiceDistance as NSString).floatValue 

     dividedDistance = fRaceDistance/fPracticeDistance 
     answer = fGoalTime/dividedDistance 

     var answerFormat : NSString = NSString(format: "%0.2f", answer) 

     lblAnswer.text = String(answerFormat) 

     return true 
    } 

fGoalTime是唯一的問題,因爲用戶會在類似打字(1:20.40)

回答

0

我假設你得到一個錯誤,這條線或者只是不正確的號碼。 var fGoalTime = (goalTime as NSString).floatValue 你需要寫一個輔助函數timeStringToFloat(String) -> Float

在那裏你會希望使用String.componentsSeparatedByString()也許是這樣的:

func timeStringToFloat(timeString: String) -> Float { 
    let milliseconds = timeString.componentsSeparatedByString(".")[1] 
    let seconds = timeString.componentsSeparatedByString(.)[0].componentsSepatatedByString(":")[1] 
    let minutes = timeString.componentsSeparatedByString(":")[0] 

    //now we have them all as String 
    //maybe covert to float then add 
    let time = Float(minutes) * 60 + Float(seconds) + Float("0."+milliseconds) 
    return time 

}