1⃣️循环
function toFormat(num) {
let nums = (num || 0).toString(), result = ‘’
while(nuns.length > 3) {
result = ‘,’ + nums.slice(-3) + result
nums = nums.slice(0, num.length - 3)
}
if(num) { result = num + result }
return result
}
2⃣️正则
function toFormat(num) {
return (num || 0).toString().replace(/(\d)(?=(?:\d{3})+$)/g, ‘$1,’)
}
3⃣️API
const num = 23467.99
num.toLocalString()
4⃣️ Intl.NumberFormat()
// 基本用法
new Intl.NumberFormat().format(23467.99)
// 加参数
locales: 语言
options:
{
“decimal”: 纯数字;
“currency”: 货币格式;
“percent”: 百分比;
“unit”: 单位格式
}