2014-10-28 80 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 

}