如何用Float划分输入的时间

时间:2014-10-28 17:34:46

标签: time swift floating-point divide

所以我在制作应用程序时输入一个时间(1:32.40),然后将此时间除以数字(50)。到目前为止,我把一切都变成了Float,但这显然是不对的。如何让用户像平常一样输入时间,然后将其转换为易于整除的Float? 我的计算功能目前看起来像这样

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)的内容

1 个答案:

答案 0 :(得分: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

}