js格式化数字

Posted on 2021-02-17 23:45  猫头唔食鱼  阅读(785)  评论(0编辑  收藏  举报

1.保留两位小数,千分位,加上金额前缀,可以传入字符串或数字

new Intl.NumberFormat('zh-CN', {style: 'currency', currency: 'CNY' , maximumFractionDigits: 2 }).format(123456.78967) // ¥123,456.79

2.加千分位并保留两位小数(常用)

new Intl.NumberFormat('zh-CN', {style: 'currency', currency: 'CNY' , maximumFractionDigits: 2 }).format(123456.78967) .split('¥')[1] //  123,456.79

3.仅加千分位,可以传入字符串或数字

new Intl.NumberFormat().format('3500.444')  // 3,500.444
new Intl.NumberFormat().format(3500.444)  // 3,500.444

4.加币种前缀

const number = 123456.789;
// 美元 "$123,456.79"
new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }).format(number) 
// 人民币 "¥123,456.79"
new Intl.NumberFormat('zh-CN', { style: 'currency', currency: 'CNY' }).format(number)


5.转化成百分数(注意,大于等于10的数字都不能被转化)

[0.01, 1.2, 0.0123,0.1,1,1.1].map(num => {
    return new Intl.NumberFormat(undefined, { style: 'percent', maximumFractionDigits: 2 }).format(num) 
})