最近几个小时以来我一直在挣扎。我的代码在 xcode 10.XX 中运行。在我更新到 xcode 11 后,numberFormatter 停止工作,现在我无法从字符串值中获取数字。下面的代码在 xcode 10 中给了我 552 欧元,在 xcode 11 中给了我 nil。谁能帮我找出问题所在?
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
}
最佳答案
问题是您正在使用 NumberFormatter
和 currency
的 numberStyle
来转换包含常规数字的字符串 - “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 €"
}
}
关于ios - xcode 11 中的 NumberFormatter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58326667/