数字的千分位格式化方法

方法一:数组(字串)循环法

 1 function toThousands(num) {
 2     var result = [ ], counter = 0;
 3     num = (num || 0).toString().split('');
 4     for (var i = num.length - 1; i >= 0; i--) {
 5         counter++;
 6         result.unshift(num[i]);
 7         if (!(counter % 3) && i != 0) { 
 8                 result.unshift(','); 
 9         }
10     }
11     return result.join('');
12 }
 1 function toThousands(num) {
 2     var result = '', counter = 0;
 3     num = (num || 0).toString();
 4     for (var i = num.length - 1; i >= 0; i--) {
 5         counter++;
 6         result = num.charAt(i) + result;
 7         if (!(counter % 3) && i != 0) { 
 8                 result = ',' + result; 
 9         }
10     }
11     return result;
12 }

方法二:字串截取法

 1 function toThousands(num) {
 2     var num = (num || 0).toString(), result = '';
 3     while (num.length > 3) {
 4         result = ',' + num.slice(-3) + result;
 5         num = num.slice(0, num.length - 3);
 6     }
 7     if (num) {
 8         result = num + result; 
 9     }
10     return result;
11 }

方法三:正则表达式法

1 function toThousands(num) {
2     return (num || 0).toString().replace(/(d)(?=(?:d{3})+$)/g, '$1,');
3 }

方法四:转换格式法

1 function toThousands(num) {
2     return (num || 0).toLocaleString('en-US');
3 }
原文地址:https://www.cnblogs.com/cdwp8/p/4097802.html