从过去的几个小时开始,我一直在挣扎。我的代码在Xcode10.XX中工作,在我更新到Xcode11后,numberFormatter停止工作,现在我无法从字符串值中获取数字。下面的代码在xcode 10中是552欧元,在xcode 11中是零。有人能帮我识别出问题是什么吗?
let currencyFormatter = NumberFormatter()
currencyFormatter.usesGroupingSeparator = true
currencyFormatter.numberStyle = .currency
currencyFormatter.locale = Locale(identifier: "de_DE")
if let priceString = currencyFormatter.number(from: "552") {
print(priceString) // Should Display 552 € in the German locale
}发布于 2019-10-11 00:11:16
问题是,您正在使用numberStyle为currency的NumberFormatter来转换包含常规数字"552“的字符串,该字符串不是货币字符串。这是行不通的。
您必须使用decimal样式将字符串转换为数字。之后,您可以使用currency样式将数字转换回字符串。
let formatter = NumberFormatter()
formatter.locale = Locale(identifier: "de_DE")
// string to number
formatter.numberStyle = .decimal
if let n = formatter.number(from: "552") {
print(n) // prints "552"
// number to string (formatted as currency)
formatter.numberStyle = .currency
if let s = formatter.string(from: n) {
print(s) // prints "552,00 €"
}
}https://stackoverflow.com/questions/58326667
复制相似问题