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?
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!