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?
Asked
Active
Viewed 9,983 times
5

Cœur
- 37,241
- 25
- 195
- 267

user441058
- 1,188
- 1
- 16
- 32
-
Side note, avoid using `Double` for currency: http://stackoverflow.com/questions/3730019/why-not-use-double-or-float-to-represent-currency – Alexander Jan 26 '17 at 23:17
-
`NSNumberFormatter` will easily convert that string to a number if you set it up properly. Show your attempt use of `NSNumberFormatter` in your question. – rmaddy Jan 26 '17 at 23:17
-
Argh - I only saw the .string method. Didn't realize there was a .number method. :-( – user441058 Jan 26 '17 at 23:27
2 Answers
25
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)
}

Jenny
- 2,041
- 13
- 15
-
2Note - 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. – rmaddy Jan 27 '17 at 00:01
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

Cœur
- 37,241
- 25
- 195
- 267