Intl.NumberFormat
千位符:
function formatAsRMB(num){
return new Intl.NumberFormat('zh-CN',{
style: 'decimal', //将数字格式化为十进制数
currency: 'CNY', // 货币为人民币
minimumFractionDigits: 0 // 表示不显示小数部分
}).format(num)
}
const number = 12345678
const format = formatAsRMB(number)
console.log(format)//12,345,678
百分比:
let formatPercent = new Intl.NumberFormat('zh-CN',{
style: 'percent',
minimumFractionDigits: 2,
maximumFractionDigits: 2
})
let numb = 0.402
console.log(formatPercent.format(numb)) // 40.20%
function formatPercentage(discount) {
return (discount * 100).toFixed(2) + '%'
}
console.log(formatPercentage(numb))