我想从字符串格式化货币:
let formatter = NumberFormatter()
formatter.numberStyle = .currency
formatter.numberStyle = .currency
formatter.locale = Locale(identifier: "en_US")
thetotal_balancestring = "$456.78"
let number = formatter.number(from: thetotal_balancestring)
工作正常。 但是如果我使用的是一个我从JSON获得的字符串,那么我无法正确使用它,尽管它显然是一个字符串。
if (object["total_balance"] == nil) {
thetotal_balance = 0
} else {
thetotal_balancestring = (object["total_balance"] as! String)
let formatter = NumberFormatter()
formatter.numberStyle = .currency
formatter.locale = Locale(identifier: "en_US")
if let number = formatter.number(from: thetotal_balancestring) {
let amount = number.decimalValue
print(amount)
} else {
print ("could not succeed despite string seems valid: \(thetotal_balancestring)")
}
打印:尽管字符串似乎有效,但无法成功:5,724.12
答案 0 :(得分:2)
确保其前缀为$
:
let formatter = NumberFormatter()
formatter.numberStyle = .currency
formatter.locale = Locale(identifier: "en_US")
let thetotal_balancestring = "$5,724.12"
let number = formatter.number(from: thetotal_balancestring)
结果:5724.12