Swift convert Currency string to double

蓝咒 提交于 2020-01-23 01:39:18

问题


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?


回答1:


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)
}



回答2:


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


来源:https://stackoverflow.com/questions/41884630/swift-convert-currency-string-to-double

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!