Swift 货币格式 ISO 标准转换问题

Swift Currency Format ISO Standard Conversion Issues

阅读 NSNumberFormatter 的 Apple 文档后 here I'm trying to convert currency as per the Uber API Documentation. Both documentations state that they use the ISO formatting standard, however in my code I find this to not be the case. ISO 4217 Standard here 在 ISO itself

public static func convertStringCurrencyToNumber(strCurrency:String, locale:String)->Double {
    var formatter = NSNumberFormatter()
    formatter.locale = NSLocale(localeIdentifier: "\(locale)")
    formatter.numberStyle = NSNumberFormatterStyle.CurrencyStyle
    println(formatter.numberFromString(strCurrency))
    if let converted:Double = formatter.numberFromString(strCurrency)?.doubleValue {
        return converted
    }else{
        return 0.0
    }

}

我对此功能的单元测试

func testCurrencyConversion() {
    let fiveBucks = UberReceipt.convertStringCurrencyToNumber(".00", locale: "en_US")
    println(fiveBucks)
    let tenBucks = UberReceipt.converStringCurrencyToNumber(".00", locale:"USD")
    println(tenBucks)
}

控制台日志: 可选(5.0) 零 5.0 0.0

如果我使用 "en_US" 结果如预期,即 5.0,但是如果我使用 Uber returns 作为语言环境 "USD",return 值为 0.0。根据 printing/inspecting 格式化程序转换货币时发生的情况,我发现它 return 为零。

我发现文档中关于 formatter.locale = NSLocale(...) 的内容具有误导性。根据文档 "The locale determines the default values for many formatter attributes, such as ISO country and language codes, currency code...."

我认为设置语言环境应该也设置货币代码。这是不正确的吗?如果我使用非标准 "en_US" 代码作为 ISO 代码(这应该是 Apple 文档使用的代码)"USD"

为什么我的代码可以工作

正如 Zoff Dino 所说,美元不是有效的语言环境标识符。要获得完整列表,您可以 运行:

NSLocale.availableLocaleIdentifiers() 

您说得对,设置语言环境设置了货币代码。尝试例如:

let l = NSLocale(localeIdentifier: "de_CH")
let f = NSNumberFormatter()
f.locale = l
f.currencyCode // Playground shows CHF

Locale 定义了正确的字母顺序、千位分隔符、时间和日期格式、货币代码和其他内容。您传入的不是语言环境,而是货币代码。如果您想从货币代码构建区域设置,您可以从 NSLocale.availableLocaleIdentifiers() 的输出和生成的货币代码创建一个查找 table。

如果您弄清楚 API 返回的内容以及您想用它做什么,可能会有所帮助。

public static func convertStringCurrencyToNumber(strCurrency:String, locale:String)->Double {
    var formatter = NSNumberFormatter()
    formatter.currencyCode = locale
    formatter.numberStyle = NSNumberFormatterStyle.CurrencyStyle
    if let converted:Double = formatter.numberFromString(strCurrency)?.doubleValue {
        return converted
    }else{
        return 0.0
    }
}

将 formatter.locale 更改为 formatter.currencyCode 可按预期使用 ISO 4127 国家和货币代码 "USD"。