FloatValue,带有来自textField的2位小数

时间:2015-01-13 21:19:39

标签: ios swift

在我的核心数据应用程序中,我从3个UITexFields中保存3个浮点数。要做到这一点,我必须将它们转换为字符串。

现在问题是这些值四舍五入为.0

我该怎么做?

nyTankning.liter = (textFieldLiter.text as NSString).floatValue
nyTankning.kronor = (textFieldKronor.text as NSString).floatValue
nyTankning.literpris = (textFieldLiterpris.text as NSString).floatValue 

2 个答案:

答案 0 :(得分:2)

你的问题是你试图使用逗号“,”而不是句号“。”

struct Number {
    static let formatter = NumberFormatter()
}
extension String {
    var converted: String? {
        return fractionDigits()
    }
    var doubleValue: Double? {
        return Number.formatter.number(from: self)?.doubleValue
    }
    var floatValue: Float? {
        return Number.formatter.number(from: self)?.floatValue
    }
    func fractionDigits(min: Int = 2, max: Int = 2) -> String? {
        Number.formatter.decimalSeparator = "."
        if let result = Number.formatter.number(from: self) {
            Number.formatter.minimumFractionDigits = min
            Number.formatter.maximumFractionDigits = max
            return Number.formatter.string(from: result)
        } else {
            Number.formatter.decimalSeparator = ","
            if let result = Number.formatter.number(from: self) {
                Number.formatter.minimumFractionDigits = min
                Number.formatter.maximumFractionDigits = max
                return Number.formatter.string(from: result)
            }
        }
        return nil
    }
}

"1,1222".converted              // "1.12"
"2".converted                   // "2.00"

"1,1222".converted?.doubleValue  // 1.12
"2".converted?.doubleValue       // 2.0

"1,1222".converted?.floatValue   // 1.12000000476837
"2".converted?.floatValue        // 2.0

"1.1222".converted              // "1.12"
"1.1222".converted?.doubleValue  // 1.12
"1.254".converted?.floatValue    // 1.25

"1.254".fractionDigits(min: 1, max: 2) // "1.25"
"1.2".fractionDigits(min: 1, max: 2)   // "1.2"

答案 1 :(得分:0)

您可以使用NSString(format: "%.02f", nyTanking.liter)