方法一
标签:综合性能最高
原理:1. 先把数字转换成字符串
2. 字符串长度>3则进入循环,分割字符串,每次循环都取后三个,并在前加逗号
3. 当长度<3时,跳出循环,走if
function toThousands(num) {
var num = (num || 0).toString(), result = '';
while (num.length > 3) {
result = ',' + num.slice(-3) + result;
num = num.slice(0, num.length - 3);
}
if (num) { result = num + result; }
return result;
}
//例:toThousands(1234567); //输出 1,234,567
//第一次循环:result = ,567 num = 1234
//第二次循环:result = ,234,567 num = 1
//跳出循环,走if:result = 1,234,567
方法二
标签:易懂
原理:从末尾开始计算,每三个加一个逗号
function toThousands(num){
num = (num || 0).toString();
var result = '',counter = 0;
for(var i = num.length - 1; i >= 0; i--){
counter ++;
result = num.charAt(i)+result;
if(!(counter % 3) && i != 0){
result = ',' + result;
}
}
return result;
}
//例:toThousands(1234567)
//第一次循环:i = 6 counter = 1 result = 7
//第二次循环:i = 5 counter = 2 result = 67
//第三次循环:i = 4 counter = 3 result = ,567
//第四次循环:i = 3 counter = 4 result = 4,567
//第五次循环:i = 2 counter = 5 result = 34,567
//第六次循环:i = 1 counter = 6 result = ,234,567
//第七次循环:i = 0 counter = 7 result = 1,234,567
方法三
标签:正则表达式
function toThousands(num) {
return (num || 0).toString().replace(/(\d)(?=(?:\d{3})+$)/g, '$1,');
}