Reputation: 2127
Is there a way to set the NSLocale
for a NSNumberFormatter
via the currency code instead of the locale identifier in iOS?
Like, for instance, to use "USD" instead of "en_US" in any point of the locale setting?
I see there's a NSLocaleCurrencyCode object, but I'm not sure what method I can use from it to set the NSNumberFormatter's
locale
.
I'm currently using Swift, if that makes the process any easier.
EDIT: For further explanation of what I'm doing, I have a list of every single country's currency code (USD, GBP, JPY, CNY, etc...). The user picks whichever currency he's using via these codes, and then I want the NSNumberFormatter to automatically set its locale to the locale of that currency to automatically format it.
Upvotes: 1
Views: 2830
Reputation: 51911
You cannot determine a specific locale from currency code.
For example, the number of locales which have currency code USD
is 27, and NSNumberFormatter
with these NSLocale
emits formatted string with 7 variations:
"$123,456.78": [en_PR, es_US, en_MH, chr_US, en_AS, en_MP, es_SV, en_VG, en_VI, es_PR, haw_US, en_IO, en_UM, en_US, en_DG, en_GU]
"US$123,456.78": [en_PW, sn_ZW, en_ZW, en_TC, nd_ZW, en_FM]
"$123.456,78": [es_EC]
"123 456,78 US$": [pt_TL]
"$ 123456.78": [en_US_POSIX]
"$ 123.456,78": [nl_BQ]
"$ 123,456.78": [lkt_US]
If you want do what you want, you should maintain a lookup table by yourself.
let currency2locale = [
"USD": NSLocale(localeIdentifier: "en_US"),
"GBP": NSLocale(localeIdentifier: "en_GB"),
"JPY": NSLocale(localeIdentifier: "ja_JP"),
...
]
Upvotes: 6