How to get an NSNumber from a String of decimal?

Viewed 51

I'm not sure what I'm doing wrong, but NumberFormatter fails to get a number from a simple decimal String when using the number(from:) method.

Here's an example:

let decimalString: String = "12.5"
let formatter = NumberFormatter()
let number = formatter.number(from: decimalString)
print(number) // nil

Please keep in mind that I'm using NumberFormatter to handle decimals from any locale, so passing "١٢٫٥" should also lead to a non-nil return value from number(from:).

What is the correct and locale-aware way of converting any string from a UITextField that is entered using keyboard type .decimalPad to a valid NSNumber and get the doubleValue from it? (shortcuts like using the Double initializer or the .asciiCapableNumberPad keyboard type are not ideal)

0 Answers
Related