js数字千分位分隔符

引言

将普通的数字转换成带千位分隔符格式的数字是一个比较常见的问题,对于千位分隔符格式是将数字的整数部分每三位分成一组,以“,”分节,小数部分不做处理。这样既方便阅读又可以使页面更加整洁。

方法一:

实现思路:将数字转换成字符数组,循环整个数组,每三位添加一个逗号。因为分隔符在顺序上是从后往前进行添加,所以方便起见可以将数组倒序过来,处理完后再倒序回去。注意小数部分的处理。

const a = 12345678;
const b = 123456.789;

function numFormat(number) {
  const num = number.toString().split('.');
  const leftNum = num[0].split('').reverse();
  const result = leftNum.reduce((init, it, index) => {
    return (index % 3 === 0 && index != 0 ? it + ',' : it) + init;
  }, '');
  return num[1] ? result + '.' + num[1] : result;
}

console.log(numFormat(a)); // 12,345,678
console.log(numFormat(b)); // 123,456.789
方法二:

使用正则表达式

const a = 12345678;
const b = 123456.789;

function numFormat(num) {
  return num.toString().replace(/\d+/, (n) => {
    return n.replace(/(\d)(?=(\d{3})+$)/g, ($1) => $1 + ',')
  })
}

console.log(numFormat(a)); // 12,345,678
console.log(numFormat(b)); // 123,456.789
方法三:

使用 js 中自带的函数toLocaleString(), 用法详细请看MDN

const a = 12345678;
const b = 123456.7888;

console.log(a.toLocaleString()); // 12,345,678
console.log(b.toLocaleString()); // 123,456.789 (小数部分四舍五入了)
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值