swift - 按国家 ISO 获取 NumberFormatter 货币

标签 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

最佳答案

我有一款应用程序可以满足您的要求。它允许用户选择特定的货币代码,然后货币值可以在用户自己的区域设置中格式化,但使用特定的货币代码。

我所做的是根据用户自己的区域设置和特定货币代码创建自定义区域设置标识符。然后,该自定义语言环境将用作货币样式的常规 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 ¥

关于swift - 按国家 ISO 获取 NumberFormatter 货币,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52060289/

相关文章:

ios - iPhone : How to get number from string with currency symbol in Objective-C

swift - 从 'table view' 和 'filtered search bar' 删除行不起作用

ios - 我想使用框架 UIViewController 作为项目类的父类(super class)协议(protocol)

ios - 以编程方式添加的 UIView 的动画将宽度分成两半

SwiftUI - 如何通过函数(使用 slider )更新值?

ios - 如何在swift 4中使用 "WWCalendarTimeSelector"第三方

swift - XLPagerTabStrip : My title label in tab bar not fully showed

json - 为什么我的文本没有添加到我的标签中?

swift - NSNumberFormatter 将 0.5 更改为 .50

iphone - 我如何从货币名称列表中获取区域设置