浏览器已经内置了对数字做格式化处理的 NumberFormat
API,它是 Intl 命名空间下的一个构造器属性,使用起来很强大。以下是我根据 MDN 文档的介绍,摸索到的几个比较实用的格式化场景。
NumberFormat
API 的语法如下:
new Intl.NumberFormat([locales[, options]])
复制代码
一、千分位逗号分隔
new Intl.NumberFormat().format(3500) // "3,500"
new Intl.NumberFormat().format('3500') // "3,500"。数字字符也能正确处理
复制代码
二、最少 & 最多保留几位小数
最多保留 4 位小数
new Intl.NumberFormat(undefined, { maximumFractionDigits: 4 }).format(123456.78967)
// "123,456.7897"
复制代码
最少两位,最多四位
[1234, 1234.6, 1234.68, 1234.685, 123456.78967].map(num => {
return new Intl.NumberFormat(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 4 }).format(num)
})
// ["1,234.00", "1,234.60", "1,234.68", "1,234.685", "123,456.7897"]
复制代码
三、加币种前缀
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)
// 日元 "¥123,457"
new Intl.NumberFormat('ja-JP', { style: 'currency', currency: 'JPY' }).format(number)
// 韩元 "₩123,457"
new Intl.NumberFormat('ko-KR', { style: 'currency', currency: 'KRW' }).format(number)
复制代码
- 国家码:saimana.com/list-of-cou…
- 国家币种列表以及默认保留的小数点位数,参看这里的列表:www.currency-iso.org/en/home/tab…。
四、总量统计(以易于阅读的形式)
const nums = [1234, 123456.78967, 1223562434, 1223562434454, 12235624344544165]
nums.map(num => {
return new Intl.NumberFormat('en-US', { notation: "compact" }).format(num)
})
// ["1.2K", "123K", "1.2B", "1.2T", "12,236T"]
nums.map(num => {
return new Intl.NumberFormat('zh-CN', { notation: "compact" }).format(num)
})
// ["1234", "12万", "12亿", "1.2万亿", "12,236万亿"]
nums.map(num => {
return new Intl.NumberFormat('ja-JP', { notation: "compact" }).format(num)
})
// ["1234", "12万", "12億", "1.2兆", "12,236兆"]
nums.map(num => {
return new Intl.NumberFormat('ko-KR', { notation: "compact" }).format(num)
})
// ["1.2천", "12만", "12억", "1.2조", "12,236조"]
复制代码
格式化默认短格式的,以 en-US 为例,想要显示为长格式的,需要设置 compactDisplay: "long"
选项。
nums.map(num => {
return new Intl.NumberFormat('en-US', { notation: "compact", Display: "long" }).format(num)
})
// ["1.2 thousand", "123 thousand", "1.2 billion", "1.2 trillion", "12,236 trillion"]
复制代码
五、百分比显示
[0.01, 1.2, 0.0123].map(num => {
return new Intl.NumberFormat(undefined, { style: 'percent', maximumFractionDigits: 2 }).format(num)
})
// ["1%", "120%", "1.23%"]
复制代码
(完)