通过国家/地区ISO获取NumberFormatter货币

时间:2018-08-28 14:26:45

标签: swift swift4 nsnumberformatter

我创建了一大堆国家/地区货币及其ISO代码。

示例:

 "USD" - "United States"
 "EUR" - "Euro"
 "JPY" - "Yen"

用户选择其自定义货币,然后将其存储在UserDefaults中。

在我的数字格式化程序中,如何通过输入iso代码使货币显示出来?

我有类似的东西,但似乎无法正常工作。

 let formatter = NumberFormatter()

 let locale = Locale.availableIdentifiers.map { Locale(identifier: $0) }.first { $0.currencyCode == "EUR" }

// Instead of EUR I would display the user defaults. Testing Purposes Only.

 formatter.numberStyle = .currency
 formatter.locale  = locale as Locale
 formatter.maximumFractionDigits = 2
 $0.formatter = formatter

2 个答案:

答案 0 :(得分:1)

我有一个应用程序可以满足您的要求。它允许用户选择特定的货币代码,然后可以使用特定的货币代码在用户自己的语言环境中格式化货币值。

我要做的是基于用户自己的语言环境和特定的货币代码创建自定义语言环境标识符。然后,将该自定义语言环境用作常规NumberFormatter设置的语言环境,以进行货币样式设置。

// Pull apart the components of the user's locale
var locComps = Locale.components(fromIdentifier: Locale.current.identifier)
// Set the specific currency code
locComps[NSLocale.Key.currencyCode.rawValue] = "JPY" // or any other specific currency code
// Get the updated locale identifier
let locId = Locale.identifier(fromComponents: locComps)
// Get the new custom locale
let loc = Locale(identifier: locId)

// Create a normal currency formatter using the custom locale
let currFmt = NumberFormatter()
currFmt.locale = loc
currFmt.numberStyle = .currency

所有这些都假定您希望数字出现,就像当前用户希望数字出现一样。数字格式不受所选货币代码的影响。甚至货币符号在结果输出中的位置也不受特定代码的影响。

美国用户会看到货币格式如下:

  

$ 1,234.56
  €1,234.56
  ¥1,235

在德国的用户会看到:

  

1.234,56 $$
  1.234,56€
  1.235¥

答案 1 :(得分:0)

您可以执行以下操作:

if let userLocaleName = UserDefaults.standard.string(forKey: "put here the string used to store the the locale"),
    !userLocaleName.isEmpty
{
    formatter.locale = Locale(identifier: userLocaleName)
}
//if the user locale is not set, revert to the default locale
else if let defaultLocaleName = Locale.availableIdentifiers.first(where: {Locale(identifier: $0).currencyCode == "EUR"})
{
    let defaultLocale = Locale(identifier: defaultLocaleName)
    formatter.locale = defaultLocale
} else {
    fatalError("Error setting the locale")
}

上面的代码中使用了if-let构造,以避免强制展开可选变量。

然后设置其余的格式化程序属性:

formatter.numberStyle = .currency
formatter.maximumFractionDigits = 2