如果数字较大时,很多时候都需要进行千位符格式化显示,方便查看,我常用的方法有以下几种:
方法1:
使用toLocaleString直接进行转换
const num = 2333333;
num.toLocaleString(); // 2,333,333
方法2:先将数字转换成字符串,再转成数组,然后进行循环,为3的倍数时添加逗号,性能不如方法3
function toThousands(num) {
let result = [ ], counter = 0;
num = (num || 0).toString().split('');
for (let i = num.length - 1; i >= 0; i--) {
counter++;
result.unshift(num[i]);
if (!(counter % 3) && i != 0) {
result.unshift(',');
}
}
return result.join('');
}
方法3:将数字转换成字符串,直接对字符串进行循环,charAt()方法是字符串处理方法,返回某个位置的内容
function toThousands(num) {
let result = '', counter = 0;
num = (num || 0).toString();
for (let i = num.length - 1; i >= 0; i--) {
counter++;
result = num.charAt(i) + result;
if (!(counter % 3) && i != 0) {
result = ',' + result;
}
}
return result;
}
方法4:正则方法
function toThousands(num) {
return (num || 0).toString().replace(/(\d)(?=(?:\d{3})+$)/g, '$1,');
}