Skip to content

Instantly share code, notes, and snippets.

@dfkaye
Last active July 2, 2020 18:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dfkaye/70014de717607c22b1bf917f170ff482 to your computer and use it in GitHub Desktop.
Save dfkaye/70014de717607c22b1bf917f170ff482 to your computer and use it in GitHub Desktop.
formatCurrency, formatting with exponent and currency
// 20 May 2019
// formatCurrency, i18n
/**
* @function formatCurrency accepts an object containing value, currency, and
* exponent fields, and returns a string containing an currency- and exponent-
* based value.
*
* @param {Number} value
* @param {Number} exponent
* @param {String} currency
*
* @returns {String} formatted value
*/
function formatCurrency(amount) {
var n = amount.value / Number('1e' + amount.exponent) || '0'
var s = (n).toLocaleString({currency: amount.currency});
return s + ' ' + (amount.currency || '?');
}
[
{
value: 1123456,
currency: 'GBP',
exponent: 2,
locale: 'gb-GB'
},
{
value: 987654321,
currency: 'DINARS',
exponent: 2,
locale: 'ar-IQ'
},
{
value: null,
currency: '',
exponent: 0,
locale: ''
}
].map(function(amount) {
console.log(formatCurrency(amount))
});
/*
11,234.56 GBP
٩٬٨٧٦٬٥٤٣٫٢١ DINARS
0 ?
*/
// 20 May 2019
// currency formatting with exponent and currency
var currencies = {
USD: '$',
GBR: '£',
EUR: '€'
}
function money(amount) {
var v = Number(amount.value)
var d = v / Number('1e' + amount.exponent)
var c = currencies[amount.currency] || amount.currency
return d + ' ' + amount.currency
}
/* test it out */
var tests = [
{
value: '6001',
exponent: '2',
currency: 'USD'
},
{
value: '16002',
exponent: '2',
currency: 'GBR'
},
{
value: '126003',
exponent: '2',
currency: 'EUR'
},
{
value: '123456',
exponent: '3',
currency: 'فلس' // dinars
}
];
var results = tests.map(function(test) {
return money(test)
});
console.log(
JSON.stringify(results, null, 2)
);
/*
[
"60.01 USD",
"160.02 GBR",
"1260.03 EUR",
"123.456 فلس"
]
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment