convert digital display format
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
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"
in addition to the other excellent solution
var n = 999999
var s = n.toLocaleString()
精彩评论