js格式化数字 金额按千位逗号分隔

// 返回数字
function removeFormatMoney(s) {
    return parseFloat(s.replace(/[^\d\.-]/g, ""));
}

/* 
 * formatMoney(s,type) 
 * 功能:金额按千位逗号分隔
 * 参数:s,需要格式化的金额数值. 
 * 参数:type,判断格式化后的金额是否需要小数位. 
 * 返回:返回格式化后的数值字符串. 
 */ 
function formatMoney(s, type) {
    if (/[^0-9\.]/.test(s))
        return "0.00";
    if (s == null || s == "null" || s == "")
        return "0.00";
    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];
        }
    }
    return s;
}

转载:http://blog.csdn.net/evangel_z/article/details/12839657

你可能感兴趣的:(js)