金额格式化 处理千分位 金额逗号,隔开

方法1.

//处理千分位使用
var dealThousands = function(value) {
    if (value === 0) {
        return parseFloat(value).toFixed(2);
    }
    if (value != "") {
        var num = "";
        value += "";//转化成字符串
        value = parseFloat(value.replace(/,/g, '')).toFixed(2);//若需要其他小数精度,可将2改成变量
        if (value.indexOf(".") == -1) {
            num = value.replace(/\d{1,3}(?=(\d{3})+$)/g, function(s) {
                return s + ',';
            });
        } else {
            num = value.replace(/(\d)(?=(\d{3})+\.)/g, function(s) {
                return s + ',';
            });
        }
    } else {
        num = ""
    }
    return num;
}

image.png

方法2.

/*
 * formatMoney(s,type)
 * 功能:金额按千位逗号分割
 * 参数:s,需要格式化的金额数值.
 * 参数:type,(number类型)金额的小数位.
 * 返回:返回格式化后的数值.
 */
var formatMoney= (val,type) => {
    if(val === '' || val === 0) return '0.00'
    val = Number(val)
    if(isNaN(val)) return ''
    return val.toFixed(type).replace(/(\d)(?=(\d{3})+\.)/g, '$1,')
  }

image.png

方法3.

formatMoney = function(s, type) {
    // if (/[^0-9\.]/.test(s))
    //     return "0.00";
    // if(isNaN(val)) return ''
    if (s == null || s == "" || s == 0)
        return "0.00";
    s = Number(s)
    var result = s;
    if(s<0){
        s=0 - s;
    }
    if(isNaN(s)) return ''
    s = s.toString().replace(/^(\d*)$/, "$1.");
    s = (s + "00").replace(/(\d*\.\d\d)\d*/, "$1");
    s = s.replace(".", ",");
    var re = /(\d)(\d{3},)/;
    while (re.test(s))
        s = s.replace(re, "$1,$2");
    s = s.replace(/,(\d\d)$/, ".$1");
    if (type == 0) {// 不带小数位(默认是有小数位)
        var a = s.split(".");
        if (a[1] == "00") {
            s = a[0];
        }
    }
    if(result<0){
        s = '-'+s
    }
    return s;
}

image.png

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值