0

How can I take a JavaScript integer of arbitrary length, such as 1234567890, and format it as a string "1,234,567,890"?

SRobertJames
  • 8,210
  • 14
  • 60
  • 107

3 Answers3

2

You can use toLocaleString() for the format that you have asked.

var myNum = 1234567890;
var formattedNum = myNum.toLocaleString();
kameswarib
  • 133
  • 7
  • 2
    Good point, but [browser support is limited](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString#Browser_compatibility) – Travis Dec 12 '14 at 15:57
0

My solution:

var number = 1234567890;
var str = number + "";
var result = str.split('').map(function (a, i) { 
    if ((i - str.length) % 3 === 0 && i !== 0) { 
        return ',' + a;
    } else { 
        return a;
    } 
}).join('');

See fiddle.

lante
  • 7,192
  • 4
  • 37
  • 57
0

The best way is probably with a regular expression. From How to print a number with commas as thousands separators in JavaScript:

function numberWithCommas(x) {
    return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
Community
  • 1
  • 1
Travis
  • 1,463
  • 11
  • 12