英文:
How to allow user to specify currency format in Swift
问题
我很好奇,是否有人对如何使用在 WWDC21 Foundation 新内容视频 中介绍的 formatted
方法来让用户控制 Double/Float 转换为货币值感到好奇?
以下是视频中的代码片段:
let price = 29
let priceFormatted = price.formatted(.currency(code: "usd"))
// priceFormatted is "$29.00"
print(priceFormatted)
我想为用户提供一个界面,让他们可以选择使用操作系统基于设备设置提供的默认选项,或者选择某个特定选项(例如日元)。所以我认为有两个关键问题:
-
.currency(code:)
方法可以接受哪些货币代码?我也希望有一些 API 可以提供代码(例如“usd”)到本地化标签(例如英文中的“U.S. Dollars”)的映射,以便我可以向用户展示。 -
我如何询问操作系统获取与语言环境设置相关的默认货币代码?
英文:
I'm curious, does anyone have suggestions on how to give users control over the conversion of Double/Float to a currency value using the formatted
methods introduced in WWDC21 What's new in Foundation video?
Here's the code snippet from the video:
let price = 29
let priceFormatted = price.formatted(.currency(code: "usd"))
// priceFormatted is "$29.00"
print(priceFormatted)
I would like to give the user an interface that lets them choose between a default that the OS supplies based on device settings, and choosing something specific (eg Japanese Yen). So I guess that boils down to two things:
-
What is the list of codes that the
.currency(code:)
method can take? I’d also like it if there was some API that gave me a mapping from codes (eg “usd”) to localized label I can present the user (eg “U.S. Dollars” in English). -
How do I ask the OS for the code that would be the default for the locale settings?
答案1
得分: 2
本地化货币信息由Foundation中的Currency结构封装。
可以使用Locale.Currency.isoCurrencies
访问标准货币列表(符合ISO 4217)。但由于该列表可能过于详尽,您可能更喜欢使用Locale.commonISOCurrencyCodes
,该列表大约只有一半的条目(目前为156条,与304条相比)。
您可以使用给定的Locale
上的localizedString(forCurrencyCode:)
方法获取每个货币代码的本地化标签。
最后,您可以使用以下方式获取设备设置的默认货币代码:
let defaultCurrencyCode = Locale.current.currency?.identifier
向@HangarRash表示赞赏,因为他的快速回复!
英文:
Localised currency information is encapsulated by the Currency structure in Foundation.
A list of the standard currencies (conforming to ISO 4217) can be accessed using Locale.Currency.isoCurrencies
. But as that list is probably too exhaustive, you might prefer to use Locale.commonISOCurrencyCodes
which has roughly half the entries (156 vs 304 at this time).
You can get a localised label for each code using the localizedString(forCurrencyCode:)
method on a given Locale
.
Finally, you can get the default currency code for your device's settings using:
let defaultCurrencyCode = Locale.current.currency?.identifier
Kudos to @HangarRash for his quick response!
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论