js 每三位数添加逗号
2021-01-23 09:15
标签:count bst OLE pre ber color float UNC for js 每三位数添加逗号 标签:count bst OLE pre ber color float UNC for 原文地址:https://www.cnblogs.com/Blogzlj/p/13279098.htmlfunction 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 || ‘‘;
}
let A1 = 1234567890122;
let A2 = 1234567890122.122;
console.log(toThousands(A1)); //1,234,567,890,122
console.log(toThousands(A2)); // 1,234,567,890,122.122
上一篇:JS中关于Number的用法