Swift convert Currency string to double

user441058 picture user441058 · Jan 27, 2017 · Viewed 8.5k times · Source

I have a string, "$4,102.33" that needs to be converted to double. This will always be US. My only way is a hack to strip out the $ and , and then convert to double. Seems like NSFormatter only lets me convert TO a currency and not from it. Is there a built-in function or better way than just removing the $ and ,? prior to converting it to double?

Answer

Jenny picture Jenny · Jan 27, 2017

NumberFormatter can convert to and from string. Also Double cannot represent certain numbers exactly since it's based 2. Using Decimal is slower but safer.

let str = "$4,102.33"

let formatter = NumberFormatter()
formatter.numberStyle = .currency

if let number = formatter.number(from: str) {
    let amount = number.decimalValue
    print(amount)
}