Open cjfff opened 5 years ago
function format(num) {
return String(num).split('').reverse().join('').replace(/(?!\d{3}$)(?!\d*\.)(\d{3})/g, '$&,').split('').reverse().join('')
}
console.log(format(1)) // 1
console.log(format(10)) // 10
console.log(format(100)) // 100
console.log(format(1000)) // 1,000
console.log(format(10000)) // 10,000
console.log(format(100000)) // 100,000
console.log(format(1000000)) // 1,000,000
console.log(format(35235235)) // 35,235,235
console.log(format(35235235.123123)) // 35,235,235.123123
const formatMoney = n => n.toLocaleString("en-US");
// const formatMoney = n => new Intl.NumberFormat().format(n);
// 两种方法都可以,但是有缺点 -> 精度不够
console.log(formatMoney(1)); // 1
console.log(formatMoney(10)); // 10
console.log(formatMoney(100)); // 100
console.log(formatMoney(1000)); // 1,000
console.log(formatMoney(10000)); // 10,000
console.log(formatMoney(100000)); // 100,000
console.log(formatMoney(1000000)); // 1,000,000
console.log(formatMoney(35235235)); // 35,235,235
接受的数字范围: 0 <= n < 2147483647