Search code examples
javascriptjsoncurrency

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

  • 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'));