FloatValue,带有来自textField的2位小数 [英] FloatValue with 2 decimals from textField
本文介绍了FloatValue,带有来自textField的2位小数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在我的核心数据应用程序中,我从3个UITexFields中保存了3个浮点数。要做到这一点,我必须将它们转换为字符串。
In my Core Data app I save 3 Floating point numbers from 3 UITexFields. To do that I had to convert them to Strings.
现在的问题是值被舍入到 .0
。
Now the problem is that the values are rounded to .0
.
我该怎么做?
nyTankning.liter = (textFieldLiter.text as NSString).floatValue
nyTankning.kronor = (textFieldKronor.text as NSString).floatValue
nyTankning.literpris = (textFieldLiterpris.text as NSString).floatValue
推荐答案
你的问题是你试图使用逗号,代替句点。
Your problem there is that you are trying to use a comma "," instead of a period "."
extension String {
var converted: String {
return fractionDigits()
}
var toDouble: Double {
return NSNumberFormatter().numberFromString(self)!.doubleValue
}
var toFloat: Float {
return NSNumberFormatter().numberFromString(self)!.floatValue
}
func fractionDigits(min:Int = 2, max:Int = 2)-> String {
let styler = NSNumberFormatter()
styler.minimumFractionDigits = min
styler.maximumFractionDigits = max
let converter = NSNumberFormatter()
converter.decimalSeparator = "."
if let result = converter.numberFromString(self) {
return styler.stringFromNumber(result)!
} else {
converter.decimalSeparator = ","
if let result = converter.numberFromString(self) {
return styler.stringFromNumber(result)!
}
}
return ""
}
}
"1,1222".converted // "1.12"
"2".converted // "2.00"
"1,1222".converted.toDouble // 1.12
"2".converted.toDouble // 2.0
"1,1222".converted.toFloat // 1.12000000476837
"2".converted.toFloat // 2.0
"1.1222".converted // "1.12"
"1.1222".converted.toDouble // 1.12
"1.254".converted.toFloat // 1.25
"1.254".fractionDigits(min: 1, max: 2) // "1.25"
"1.2".fractionDigits(min: 1, max: 2) // "1.2"
这篇关于FloatValue,带有来自textField的2位小数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文