I'm trying to create a function that will format a number received from the user's input so that it will add commas in the right places. For example, a 1000 becomes a 1,000. A 1000000 becomes a 1,000,000 an so on.
var formatNumber = function (num) {
var numSplit, dec, int;
num = Math.abs(num);
num = num.toFixed(2);
numSplit = num.split('.');
int = numSplit[0];
dec = numSplit[1];
if (int.length > 3 && int.length <= 6) {
int = int.substr(0, int.length - 3) + ',' + int.substr(int.length - 3, 4);
} else if (int.length > 6) {
int = int.substr(0, int.length - 6) + ',' + int.substr(int.length - 6, int.length - 4) + ',' + int.substr(int.length - 3, 7);
}
return int + '.' + dec
}
The function works great for numbers with up to 7 digits. 1 million turns into 1,000,000.00 perfectly, but above that it adds another zero, so a 10 million becomes 10,0000,000.00 . How can this be fixed?
Here's a codepen: https://codepen.io/samivino/pen/ZEzRjjy
P.s.- Numbers higher than 999,999,999 are not relevant, so there's no need to add more that 2 commas.