在我们展示金额的时候,在大金额下阅读比较困得,采用每千分位添加一位逗号,来展示数据,更容易阅读
const toThousands = (num = 0) => {
return num.toString().replace(/\d+/, function(n) {
return n.replace(/(\d)(?=(?:\d{3})+$)/g, '$1,');
});
};
console.log(toThousands(1234567890.111)); //1,234,567,890.111
const toThousands = (num = 0) => {
let result = '';
let numArr = num.toString().split('.');
let int = numArr[0];
let decmial = numArr[1] ? '.' + numArr[1] : '';
for (let n = int.length - 1; n >= 0; n--) {
result += int[int.length - n - 1];
if ((int.length - n - 1) % 3 === 0 && n !== 0) {
result += ',';
}
}
return result + decmial;
};
console.log(toThousands(1234567890.111)); //1,234,567,890.111
function toThousands(num = 0) {
let result = '';
let numArr = num.toString().split('.');
let int = numArr[0];
let decmial = numArr[1] ? '.' + numArr[1] : '';
while (int.length > 3) {
result = ',' + int.slice(-3) + result;
int = int.slice(0, int.length - 3);
}
if (int) {
result = int + result;
}
return result + decmial;
}
console.log(toThousands(1234567890.111));