Your problem there is that you are trying to use a comma "," instead of a period "."
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"
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…