将一个int转换为Swift中的Float

时间:2015-02-09 01:23:08

标签: swift

我试图将计算结果(ShotPercentage)转换为Float,并将应用程序中的结果显示为89%。但我正在努力与类型铸造任何帮助将不胜感激。这是我的代码:

    // calculate shot percentage
    shotPercentage = makeCounter / totalCounter
    shotPercentageLabel.text = "\(shotPercentage)"

3 个答案:

答案 0 :(得分:0)

您可以将转化应用于Float这样的结果。

shotPercentage = Int(makeCounter / totalCounter)

答案 1 :(得分:0)

    var shotPercentageInt: Int
    shotPercentageInt = 3/5
    println("\(shotPercentageInt*100)%") // 0% because 3/5 = 0.6 -> Int = 0

    //
    var shotPercentageFloat: Float
    shotPercentageFloat = 3/5
    println("\(shotPercentageFloat*100)%") // 60.0% because 3/5 = 0.6 -> Float = 60%

    // Convert Float to Int
    var shotPercentageFloatToInt: Int
    shotPercentageFloatToInt = Int(shotPercentageFloat)
    println("\(shotPercentageFloat)") // 0.6
// It's amazing

答案 2 :(得分:0)

您可能想要使用NSNumberFormatter。它很好地用于字符串并且来自字符串。无论如何,它看起来像:

let makeCounter = 15
let totalCounter = 20
let shotPercentage:Float = makeCounter / totalCounter
let formatter = NSNumberFormatter()
formatter.numberStyle = .PercentStyle
if let percentString = formatter.stringFromNumber(shotPercentage) {
    shotPercentageLabel.text = percentString
}

在这种情况下,标签将读取75%,因为格式化程序将包含百分号。