xcode 11 中的 NumberFormatter

NumberFormatter in xcode 11

最近几个小时以来我一直在挣扎。我的代码在 xcode 10.XX 中运行。在我更新到 xcode 11 后,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
    }

问题是您使用 NumberFormattercurrencynumberStyle 来转换包含常规数字的字符串 – “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 €"
    }
}