ios - xcode 11 中的 NumberFormatter

标签 ios swift number-formatting

最近几个小时以来我一直在挣扎。我的代码在 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
    }

最佳答案

问题是您正在使用 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 €"
    }
}

关于ios - xcode 11 中的 NumberFormatter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58326667/

相关文章:

首次启动时的 iOS 用户信息

ios - 如何在 swift 4 中解决此问题 `Realm accessed from incorrect thread.`

vba - 将 Excel 中的值从字符串更改为数字

ios - didOutputSampleBuffer 委托(delegate)永远不会被调用 (iOS/Swift 3)

iOS:didSelectRowAt 索引路径仅适用于第二次点击

ios - Swift 2 - 数组是否在设置期间被复制?

cocoa - 如何不缓存由ReferencingURL加载的NSImage

ios - 根据用户在 Swift 中的方向旋转 Mapbox map

java - 如何使用 DateFormat 和 NumberFormat 为几个不同的区域设置输出相同的日期、数字、价格和百分比?

Oracle SQL - 将小数点更改为逗号