Sep 1, 2020
8
Level 9
Format a number to currency
I found this code on stackoverflow but I don't really understand it, it only does what I want when the digit is 5 numbers or below, the currency should be formatted like this:
5000 > 5,000.00
10000 > 10,000.00
150000 > 150,000.00
1000000 > 1,000,000.00
The code works for the first 2 but not the last ones
formatMoney(number) {
var decPlaces = 2;
var decSep = ".";
var thouSep = ",";
var sign = number < 0 ? "-" : "";
var i = String(parseInt(number = Math.abs(Number(number) || 0).toFixed(decPlaces)));
var j = (j = i.length) > 3 ? j % 3 : 0;
return sign +
(j ? i.substr(0, j) + thouSep : "") +
i.substr(j).replace(/(\decSep{3})(?=\decSep)/g, "" + thouSep) +
(decPlaces ? decSep + Math.abs(number - i).toFixed(decPlaces).slice(2) : "");
},
How can I get it to work as expected?
Please or to participate in this conversation.