始终以来都是本人写了一个格式化函数来解决,会应用 replace
配合正则对数字进行千位宰割来展现,并且搭配 Vue.filter
来实现疾速格式化。
然而因为我的项目须要 i18n
,所以对于大位数解决就会比拟麻烦了,因为在境内就须要应用 万位宰割,大位数应用 万、亿、万亿 来缩,而在英语系国家就会应用 千分分隔,比如说: K、M、B 来缩写数额。
刚巧最近开始了一个须要国际化的我的项目,在一开始编写数字格式化过滤器的时候偶然发现了 Intl.NumberFormat().format()
这个API,原来当初 原生JS就反对了对数字的格式化,并且不光能够千位分隔,还能够将大位数缩写。
简略的看一下这个API:
Intl.NumberFormat
是对语言敏感的格式化数字类的结构器类。
语法:new Intl.NumberFormat([locales[, options]])
是不是很简略,并且能够从参数中看到,这个API是反对设置本地化的,那就疾速来过一遍示例:
// 间接格式化new Intl.NumberFormat().format(123456789)// ’123,456,789
应用 locales
本地化数字:
// 英语环境下的数字格式化new Intl.NumberFormat('en').format(123456.789);// '123,456.789'// 中文环境下的数字格式化new Intl.NumberFormat('zh').format(123456.789);// '123,456.789'// 德语环境应用逗号(,)作为小数点,应用句号(.)作为千位分隔符new Intl.NumberFormat('de-DE').format(123456.789)// '123.456,789'// 阿拉伯语国家应用阿拉伯语数字new Intl.NumberFormat('ar-EG').format(123456.789);// ''
配置紧凑型({notation:"compact"}
) 能够将大位数缩写:
new Intl.NumberFormat('en', {notation:"compact"}).format(123456789)// '123M'new Intl.NumberFormat('en', {notation:"compact", compactDisplay: "long"}).format(123456789)// '123 million'new Intl.NumberFormat('zh', {notation:"compact"}).format(123456789)// '1.2亿'new Intl.NumberFormat('zh', {notation:"compact", compactDisplay: "long"}).format(123456789)// '1.2亿'
new Intl.NumberFormat('zh-Hans-CN-u-nu-hanidec', {notation: "compact"}).format(123456789)// 一.二亿new Intl.NumberFormat('zh-Hans-CN-u-nu-hanidec', {notation: "compact"}).format(1234567890)// '一二亿'
能够看到应用中文十进制数字,还是略微有点问题的,不过间接应用阿拉伯数字展现也不是不行对吧。
其余扩大用法查看MDN的文档就行,外面有具体的示例,我就不一一举例了。
对于兼容性
兼容性问题是有很多人关注的,作为一个在2012年被提出的标准(ECMA-402 1.0
),从 IE 11
开始被反对(不持支大位数缩写),其它的古代浏览器都是反对的,当然处在试验阶段的属性实现水平不统一,不过 format
和 locales
以及 notation
都是反对的,所以失常应用曾经足够了。
参考文档:
Intl.NumberFormat - JavaScript | MDN
Intl.NumberFormat.prototype.format() - JavaScript | MDN
Intl.NumberFormat.prototype.format - ECMAScript Internationalization API Specification – ECMA-402 Edition 1.0