Skip to content

Instantly share code, notes, and snippets.

View adamtarmstrong's full-sized avatar
🏠
Working from home

Adam T Armstrong adamtarmstrong

🏠
Working from home
View GitHub Profile
@adamtarmstrong
adamtarmstrong / money_format.js
Created August 11, 2017 19:22
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) : "");
};