前端数据格式化之Intl对象

Intl 对象是 ECMAScript 国际化 API 的一个命名空间,它提供了精确的字符串对比(Collator ),数字格式化(NumberFormat)等功能

collator这个单词意思是排序器。Intl.Collator对象是排序器的构造函数,可以支持对语言敏感的字符串比较。
语法:new Intl.Collator([locales[, options]])
参考文档:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Intl/Collator

options有个可选参数是numeric,布尔属性,是否按照数值进行比较,默认是false
如果我们对字符串进行排序,会得到一个错误的结果,但是使用Intl.Collator对象就能得到正确的结果

['13', '2', '110', '100', '12'].sort();    
// 结果是: ['100', '110', '12', '13', '2']
['13', '2', '110', '100', '12'].sort(new Intl.Collator(undefined, { numeric: true }).compare); 
// 结果是:['2', '12', '13', '100', '110']

如果我们想对中文按照拼音排序,我们会遇到以下问题

const citys= ['上海','天津','广州','武汉','四川','重庆','北京']
citys.sort()
// 结果是:['上海', '北京', '四川', '天津', '广州', '武汉', '重庆']

如果我们使用Intl.Collator对象

citys.sort(new Intl.Collator('zh').compare);
// 结果是:['北京', '重庆', '广州', '上海', '四川', '天津', '武汉']

Intl.NumberFormat可以根据不同语言环境对数值进行不同的格式化处理,他的参数和Number.toLocaleString()一样
语法:new Intl.NumberFormat([locales[, options]])
参考文档:[https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat]
常用的给金额加千分位
更多用法:https://zhuanlan.zhihu.com/p/356991916

new Intl.NumberFormat().format(1000.222);
// 结果是:'1,000.222'

如果我们想控制小数位数

new Intl.NumberFormat(undefined, {
 minimumFractionDigits: 2, //最少几位小数
 maximumFractionDigits: 2  //最多几位小数
 }).format(1000.222)
// 结果是:'1,000.22'

如果想把数字转为百分比

new Intl.NumberFormat(undefined, { style: 'percent', maximumFractionDigits: 2 }).format(0.123222) 
// 结果是:'12.32%'

如果不想要千分位

new Intl.NumberFormat(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2, useGrouping: false }).format(123456.000)
// 结果是:'123456.00'
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值