'Currency Code to locale JS

Humour me here, but I have a trivial task of taking a number input, and format it to a currency code.

IE:

var value = 1000;
value.toLocaleString('en-AU, {
    style: 'currency',
    currency: 'AUD;,
    minimumFractionDigits: 2
});
// A$1,000.00

Which works - only problem is, this sits in a function, where I pass the value and the currency..

function(value, currency)

Which now I have to maintain a list of currency to locale mappings. Is there a quick and lightweight way to format a number to currency. Im quite happy to sent a locale instead of the currency. Either way, I don't want to maintain two lists.



Solution 1:[1]

You don't need two lists. Just have a map (object), using the currency as the key, and the locale as the value.

var currencyToLocale = {
  'AUD': 'en-AU'
    // etc...
};

function formatAsCurrency(value, currency) {
  // get the locale from the map...
  var locale = currencyToLocale[currency];

  return value.toLocaleString(locale, {
    style: 'currency',
    currency: currency,
    minimumFractionDigits: 2
  });
};

console.log(formatAsCurrency(1000, 'AUD'));

Solution 2:[2]

If what you want is where to get the list of equivalences, I didn't found one, but you could build it matching these lists

currencies: http://www.currency-iso.org/dam/downloads/lists/list_one.xml

locales: http://www.science.co.il/Language/Locale-codes.asp

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 forgivenson
Solution 2 feiss