quick question, I have some integrate variable in javascript, say: 123456, or 123456789, it can be any valid number. Now, I would like to convert the number to a string like "123,456" or "123,456,789". Does anyone have a good algorithm for this? Of course, it should work for any numbers. For example: for 2000 ---> 2,000; 123456--->123,456
+1
A:
Give this a shot.
var num = 12345678;
var str = num + ""; // cast to string
var out = [];
for (var i = str.length - 3; i > 0; i -= 3) {
out.unshift(str.substr(i, 3));
}
out.unshift(str.substr(0, 3 + i));
out = out.join(','); // "12,345,678"
nickf
2009-12-22 02:21:38
+1
A:
in addition to the other excellent solution
var n = 999999
var s = n.toLocaleString()
jspcal
2009-12-22 02:29:58
+1 - (15 chars)
nickf
2009-12-22 02:41:21
This is great because it works with decimals (e.g. 999999.12345) but it doesn't insert commas for me on Chrome or Safari.
Annie
2009-12-22 02:50:03