toThousands(num) {
num = (num || 0).toString();
let number = 0,
floatNum = '',
intNum = '';
// 判断是否有小数位,有则截取小数点后的数字
if (num.indexOf('.') > 0) {
number = num.indexOf('.'); // 获取小数点出现的位置
floatNum = num.substr(number); // 截取arr.substr(form, length)
intNum = num.substring(0,number); // 截取arr.substring(start, end)
} else {
intNum = num;
}
let result = [],
counter = 0;
intNum = intNum.split('');
// 利用3的倍数,向数组插入','
for (let i = intNum.length - 1; i >= 0; i--) {
counter++;
result.unshift(intNum[i]);
if (!(counter % 3) && i != 0) { result.unshift(','); }
}
return result.join('') + floatNum || '';
}
const A1 = 1234567890122;
const A2 = 1234567890122.122;
console.log(toThousands(A1)); //1,234,567,890,122
console.log(toThousands(A2)); // 1,234,567,890,122.122
js展示数字的时候,每隔三位数用逗号隔开
最新推荐文章于 2022-10-14 10:51:32 发布