Localization of textField entry of Currency

I want to handle multiple currency formats in a textField which accepts a currency entry. Example: $13,245.12

If the user enters this value as the string: "13245.12" then converting it to a double works fine. However, if the user enters "13,245.12" the conversion to Double results in 'nil'.

If the original entry is "13245.12" and after conversion to a Double and then application of the NumberFormatter() we get "$13,245.12" as expected. However if the user needs to edit the value to "$13,555.12" then this value again gets converted to 'nil' when we attempt to get a Double.

Although its easy enough to remove the $ and , in code we still have an issue if we use the same code for other language formats unless we have language specific code - which seems to defeat the whole purpose of the NumberFormatter(). What is the best practice since this seems like a pretty basic issue regarding Localization for Apps that accept currency values?
Supporting free-form number input is tricky. The .currency style definitely expects the input string to have the currency symbol. If you want to allow the user to delete that, you can use the .decimal style as a backup. I’ve pasted in an example below.

IMPORTANT Constructing number formatters can be expensive. If you’re doing this a lot, you should cache a .currency and a .decimal number formatter. And if you do that you must remember to flush that cache if the locale setup changes.

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@apple.com"

Code Block
import Foundation
func number(for string: String) -> NSNumber? {
let nf = NumberFormatter()
nf.numberStyle = .currency
if let n = nf.number(from: string) {
return n
}
nf.numberStyle = .decimal
return nf.number(from: string)
}
print(number(for: "£1,234.56")?.description ?? "nil")
print(number(for: "£1234.56")?.description ?? "nil")
print(number(for: "1,234.56")?.description ?? "nil")
print(number(for: "1234.56")?.description ?? "nil")
// All of the above print "1234.56"
print(number(for: "£1,234")?.description ?? "nil")
print(number(for: "£1234")?.description ?? "nil")
print(number(for: "1,234")?.description ?? "nil")
print(number(for: "1234")?.description ?? "nil")
// All of the above print "1234"
print(number(for: "£13,555.12")?.description ?? "nil")
// All of the above print "13555.12"

Localization of textField entry of Currency
 
 
Q