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

SRobertJames
- 8,210
- 14
- 60
- 107
3 Answers
2
You can use toLocaleString() for the format that you have asked.
var myNum = 1234567890;
var formattedNum = myNum.toLocaleString();

kameswarib
- 133
- 7
-
2Good 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
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, ",");
}
-
If an existing answer solves a question, it should be marked as duplicate. – Felix Kling Dec 12 '14 at 15:58