在我的模型中,我将价格存储为NSDecimalNumber
价值观。
struct Item {
var price: NSDecimalNumber // eg. 3.543
var currencyCode: String // eg. "USD"
}
我想使用用户的正确显示它们Locale
。我找到了一个使用的解决方案NumberFormatter
:
let formatter = NumberFormatter()
formatter.numberStyle = .currency
formatter.currencyCode = item.currencyCode
formatter.string(from: item.price)
正如预期的那样,它根据用户的区域设置给出不同的结果。
如果我设置formatter.currencyCode
to USD
:
- For
"en_US"
: "$3.543"
- For
"fr_CA"
: "US$3.543"
- For
"de_DE"
: "3,543 US$"
- For
"da_DK"
: "3,543 US$"
如果我设置formatter.currencyCode
to DKK
:
- For
"en_US"
: "DKK 3.543"
- For
"fr_CA"
: "DKK 3.543"
- For
"de_DE"
: "3,543 DKK"
- For
"da_DK"
: "3,543 kr."
问题在于,对于更多外来货币(例如 DKK - 丹麦克朗),格式化程序使用currencyCode 而不是currencySymbol。我觉得使用符号而不是仅仅使用代码更有意义。
理想情况下,如果我设置formatter.currencyCode
to DKK
我想要:
- For
"en_US"
: "kr. 3.543"
- For
"fr_CA"
: "kr. 3.543"
- For
"de_DE"
: "3,543 kr."
- For
"da_DK"
: "3,543 kr."
我怎样才能实现这个目标?或者我应该坚持如何Locale.current
已设置且不触摸它?
注意:我不能使用NumberFormatter
仅适用于数字,然后手动添加货币符号,因为符号可以分配给不同的货币:$3.543
是美元价格en_US Locale
but in fr_CA Locale
这是加元的价格。
EDIT根据评论中的建议,我将价格类型更改为NSDecimalNumber
.