0

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.

Semion Vino
  • 121
  • 1
  • 9
  • 1
    `(1000000).toLocaleString()` for example ([docs](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString))? – Andy Sep 13 '19 at 13:25

1 Answers1

0

You can simply use toLocaleString()

var number = 1000000;
var formatted = number.toLocaleString();

console.log(formatted) //1,000,000

Read here for more information on how to use it.

Andy
  • 61,948
  • 13
  • 68
  • 95
Edison Biba
  • 4,384
  • 3
  • 17
  • 33
  • Beat me to it! Here’s another example using the `minimumFractionDigits` option https://stackoverflow.com/a/30106316/673457 – Ted Whitehead Sep 13 '19 at 13:28
  • `minimumFractionDigits` is only supported in newest version of browsers, but it is a good option to – Edison Biba Sep 13 '19 at 13:30
  • Browser support is actually pretty good (IE11, Android 4.4, iOS10), but not universal https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString#Browser_compatibility – Ted Whitehead Sep 13 '19 at 14:22