I'm trying to get float number
from amount
string with out currency symbol
like "100.00". Its working properly in English language. When language changed to German in device, its behaviour is getting changed. How can I achieve float value with out affecting by language change in device.
func getFloatNumberFromString(_ str: String) -> Float {
guard let number = NumberFormatter().number(from: str) else {
return 0.0
}
return number.floatValue
}
another piece of below code to deal with it:
func removeFormatAmount() -> Double {
let formatter = NumberFormatter()
formatter.numberStyle = .decimal
return formatter.number(from: self) as! Double? ?? 0
}
When I use second method then the output is coming as 0.
Please let me know what am I missing or suggest me to deal with it. Thanks in advance
In many European countries the decimal separator is a comma rather than a dot.
You could set the Locale
of the formatter to a fixed value.
func float(from str: String) -> Float {
let formatter = NumberFormatter()
formatter.locale = Locale(identifier: "en_US_POSIX")
guard let number = formatter.number(from: str) else {
return 0.0
}
return number.floatValue
}
PS: I changed the signature to fit the Swift 3+ style