Reputation: 205
I am struggling to find a good way to get the Currency Code for Intl.NumberFormat from my locale.
We have the ability for the user to change locale at any time. I need a way to retrieve the currency code based on the selected locale so that I can format appropriately.
let chosenLocale = appSettings.LocaleKey; //Could be anything user chooses en-US, ja-JP, etc..
// THIS DOES NOT EXIST, DOES ANY SUCH MAPPING, LOOKUP, OR LIST EXIST?
let currencyBasedOnLocale = GetCurrencyCodeFromLocale(chosenLocale);
// WOULD BE COOL IF THERE WAS THIS FOR ALL KNOWN CURRENCIES:
// var localeCurrencyLookup = { "en-US": "USD", "ru-RU" : "RUB", "en-GB" : "GBP", etc... }
// THEN I COULD DO THIS:
// let currencyBasedOnLocale = localeCurrencyLookup[chosenLocale] || "USD";
var formatter = new Intl.NumberFormat(chosenLocale, {
style: 'currency',
currency: currencyBasedOnLocale
});
return formatter.format(value);
So does anyone know if such a mapping of locales to currency codes exist? Or is there some other way I can find the currency code based on the locale? I feel like this is a huge oversite to not have a locale to currency mapping. Perhaps most sites only support a few locales, leaving the developer to hash it out manually. I do not mind typing out a json lookup mapping object, but I do not even know where to go to see which locales map to which currency code.
Upvotes: 3
Views: 1708
Reputation: 313
From my vue:
import { formatAmount } from 'Composables/Utils/currency'
console.log(formatAmount(15008.36, 'en-US', 'USD'))
From my ts
export const formatAmount = (amount:number, getLocale:string, getCurrency:string) => {
const locale = getLocale
const currency = getCurrency
const formats = new Intl.NumberFormat(locale, {
style: 'currency',
currency,
maximumFractionDigits: 2
})
return formats.format(amount)
}
result
$15,008.36
Use undefined in the first argument from Intl.NumberFormat to use the system locale (the user's locale).
Upvotes: -1