【问题标题】:Getting NumberFormatter Currency by Country ISO按国家 ISO 获取 NumberFormatter 货币
【发布时间】:2018-08-28 14:26:45
【问题描述】:

我创建了一个国家货币及其 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

【问题讨论】:

  • 这个列表以什么格式存储?什么是 0 美元?可以举一些这个 $0 的例子吗?
  • 该列表是一个结构数组,其中包含国家/地区 iso 和名称。然后我在我的表格视图中查看并显示每种货币。然后 $0 来自 eureka form builder - $0.formatter 只需要一个格式

标签: swift swift4 nsnumberformatter


【解决方案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 日元

【讨论】:

  • @Pegasus - 这是你要找的结果吗?
【解决方案2】:

你可以这样做:

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

【讨论】:

  • 我稍微修改了一下,它工作了!虽然,对于美元,如果我做 6525.50,我会不断得到逗号示例,我实际上得到 6.525,50
  • 它是什么语言环境?
猜你喜欢
  • 2010-09-19
  • 2015-03-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-18
  • 1970-01-01
相关资源
最近更新 更多