快速将货币字符串转换为双精度 [英] Swift convert Currency string to double

查看:113
本文介绍了快速将货币字符串转换为双精度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串, $ 4,102.33 ,需要将其转换为双精度。这将永远是美国。我唯一的方法是破解 $ ,然后转换为double。好像 NSFormatter 只能让我转换为货币,而不能转换为货币。除了删除 $ 之外,是否有内置功能或更好的方法?

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?

推荐答案

NumberFormatter 可以转换为和?从字符串。同样, Double 不能精确表示某些数字,因为它是基于2的。使用 Decimal 会更慢但更安全。

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

这篇关于快速将货币字符串转换为双精度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆