金額格式化 處理千分位 金額逗號,隔開

方法1.spa

//處理千分位使用
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.code

/*
 * 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.orm

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

相關文章
相關標籤/搜索