JS 添加千分位与去掉千分位示例

一、添加千分位

转成千分位-保留两位小数-兼容负数版

    export function thousands (n) {
        const num = NToFixed(n, 2)
        // 匹配前面是1到3个的数字后面跟着3个数字的
        const re = /\d{1,3}(?=(\d{3})+$)/g
        return  `${num}`.replace(/^(\-?)(\d+)((\.\d+)?)$/, function (s, s1, s2, s3) {
            return s1 + s2.replace(re, '$&,') + s3
        })
    }

转成千分位-保留两位小数-兼容负数版-精简

function thousands (num) {
  return (+num || 0).toString().replace(/^-?\d+/g, m => m.replace(/(?=(?!\b)(\d{3})+$)/g, ','))
}

1.1 千分位效果与问题

效果
假如一个数为1000,那么千分为会改为1,000,
问题:可能在前端拿值会丢失,如下

在这里插入图片描述

解决措施接受把千分为去除,下面博主写一个通用的去除千分为方法

二、去除千分为位

function delcommafy(num){//去除千分位中的‘,’
    if(num&&num!='undefined'&&num!='null'){
        let numS = num;
        numS = numS.toString();
        numS = numS.replace(/,/gi, '');
        return numS;
    }else {
        return num;
    }
}

运用

在这里插入图片描述
结果

在这里插入图片描述

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值