Peg*_*sus 1 nsnumberformatter swift swift4
我创建了一个国家货币及其 ISO 代码的大列表。
例子:
"USD" - "United States"
"EUR" - "Euro"
"JPY" - "Yen"
Run Code Online (Sandbox Code Playgroud)
用户选择他们的自定义货币并将其存储在 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
Run Code Online (Sandbox Code Playgroud)
我有一个应用程序可以满足您的要求。它允许用户选择特定的货币代码,然后可以在用户自己的区域设置中格式化货币值,但使用特定的货币代码。
我所做的是根据用户自己的语言环境和特定的货币代码创建一个自定义的语言环境标识符。然后将该自定义语言环境用作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
Run Code Online (Sandbox Code Playgroud)
这一切都假设您希望数字像当前用户期望的数字那样出现。数字格式不受所选货币代码的影响。甚至货币符号在结果输出中的位置也不受特定代码的影响。
美国的用户会看到格式如下的货币:
1,234.56 美元 1,234.56
欧元
1,235 日元
而德国的用户会看到:
1.234,56 $
1.234,56 €
1.235 ¥
| 归档时间: |
|
| 查看次数: |
900 次 |
| 最近记录: |