Perhaps the simplest solution would be if toLocaleString could be combined with toFixed, but that doesn't seem practical.
toLocaleString can be used to format numbers according to different languages (the term "locale" is a misnomer) and currencies. However, while ECMA-402 (on which the options to toLocaleString are based) uses the established ISO 3217 codes for currencies, it allows implementations to vary their representation so users may get standard codes for some (e.g. FJD for Fiji dollar), non–standard letters and symbols for a few (e.g. NZ$ for New Zealand dollar), and just symbols for others (e.g. $ for US dollar) (see EMCA-402 §6.3).
So users are still left wondering which currency a symbol represents for currencies used in multiple countries, e.g.
- Is $ for US, Australian, New Zealand or Fiji dollar (and many others)?
- Is £ for British, Lebanese or Egyptian pound (and many others)?
If you have an application that you want to accurately reflect currencies in a format familiar to the user:
- Prefix the number with the correct ISO 3217 code
- Specify the language as undefined
- Format the number using the required number of decimal places.
E.g.
var num = 3000000;
var currencies = ['USD','NZD','FJD','EUR','GBP','EGP','LBP','MRO','JPY']
console.log('toString variants (the first 3 are all dollars)\n');
currencies.forEach(function(c){
console.log(c + ': ' + num.toLocaleString(undefined, {style: 'currency', currency: c}));
});
console.log('Consistent with ISO 4217\n');
currencies.forEach(function(c) {
console.log(c + ': ' + c + num.toLocaleString(undefined,
{minimumFractionDigits: 2, maximumFractionDigits: 2}));
});
Using the ISO currency code means all currencies are treated equally and there's no confusion over symbology.
There are only two countries that don't use decimal currencies: Madagascar (1 ariary = 5 iraimbilanja) and Mauritania (1 ouguiya = 5 khoums). toLocaleString doesn't do anything special with those currencies, so you'll need special handling if you wish to accommodate their minor units. You may want to support older (or ancient) non–decimal currencies like the old British pound or Greek drachma, but you'll need special handling for those too.