Swift convert Currency string to double
Asked Answered
T

2

6

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?

Tucker answered 26/1, 2017 at 23:10 Comment(3)
Side note, avoid using Double for currency: #3730519Tampere
NSNumberFormatter will easily convert that string to a number if you set it up properly. Show your attempt use of NSNumberFormatter in your question.Selina
Argh - I only saw the .string method. Didn't realize there was a .number method. :-(Tucker
C
26

NumberFormatter can convert to and from string. Also Double cannot represent certain numbers precisely since it's base-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)
}
Copyread answered 26/1, 2017 at 23:28 Comment(1)
Note - If the string is always going to be formatted as USD, you will need to set the formatter's locale to en_US. If you don't, the string won't be parsed properly in most other locales.Selina
A
5

To convert from String to NSNumber for a given currency is easy:

let formatter = NumberFormatter()
formatter.numberStyle = .currency
formatter.locale = Locale(identifier: "en_US")
let number = formatter.number(from: string)

To get your number as a Double or as a Decimal (preferred) is then direct:

let doubleValue = number?.doubleValue
let decimalValue = number?.decimalValue
Aubin answered 27/1, 2017 at 2:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.