Created
August 11, 2017 19:22
-
-
Save adamtarmstrong/ea0d08e9431aeb5df72970c2c07f963d to your computer and use it in GitHub Desktop.
JS - Format Number as Currency
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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