Skip to content

Instantly share code, notes, and snippets.

@adamtarmstrong
Created August 11, 2017 19:22
Show Gist options
  • Save adamtarmstrong/ea0d08e9431aeb5df72970c2c07f963d to your computer and use it in GitHub Desktop.
Save adamtarmstrong/ea0d08e9431aeb5df72970c2c07f963d to your computer and use it in GitHub Desktop.
JS - Format Number as Currency
exports.format = function(number, decimals, decSymbol, thousSymbol) { //number, decimal places , decimal symobl (.), thousands separator (,)
decimals = isNaN(decimals = Math.abs(decimals)) ? 2 : decimals,
decSymbol = decSymbol == undefined ? "." : decSymbol,
thousSymbol = thousSymbol == undefined ? "," : thousSymbol,
posNegSymbol = number < 0 ? "-" : "",
i = parseInt(number = Math.abs(+number || 0).toFixed(decimals)) + "",
j = (j = i.length) > 3 ? j % 3 : 0;
return posNegSymbol + '$' + (j ? i.substr(0, j) + thousSymbol : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + thousSymbol) + (decimals ? decSymbol + Math.abs(number - i).toFixed(decimals).slice(2) : "");
};
/*
* var money = require('money_format');
* money.format(numberToFormat,0);
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment