NSNumberFormatter.numberFromString returns unexpected values

217 views Asked by At

I've met an issue when using NSNumberFormatter. In two system language settings, I get two different results.

Say the system language is Vietnamese now. When the value is "1.111", which contains the currencyGroupingSeparator, numberFromString returns nil. But when the value is "111", which doesn't contain the currencyGroupingSeparator, numberFromString returns NSNumber(1.111) as expected .

The weird thing is when the system language is English, both "1.111" and "111" can be converted by numberFromString to expected `NSNumber(1.111 and 111).

Do I misuse NSNumberFormatter?

let formatter = NSNumberFormatter()
formatter.numberStyle = .CurrencyStyle
formatter.currencySymbol = ""
formatter.maximumFractionDigits = 0
formatter.minimumFractionDigits = 0
formatter.currencyGroupingSeparator = "."
formatter.currencyDecimalSeparator = ","
let testNumber = formatter.numberFromString("1.111")

// nil when system language is Vietnamese,
// but 1.111 when system language is English 
print("\(testNumber)") 
1

There are 1 answers

0
Tj3n On

You can just force the locale for the formatter, then it will be the same for all cases:

formatter.locale = NSLocale(localeIdentifier: "en_US")