js 实现逗号分隔,即每隔三位一个间隔

1,toLocaleString();

var a = 8462948.24;
a.toLocaleString();

2,正则封装成方法

/

function formatNum(strNum){
        var outputmoney = function (number) {
            number = number.replace(/\,/g, "");   //把所有的逗号,清除
            if (isNaN(number) || number == "")return "";
            number = Math.round(number * 100) / 100;
            if (number < 0)
                return '-' + outputdollars(Math.floor(Math.abs(number) - 0) + '') + outputcents(Math.abs(number) - 0);
            else
                return outputdollars(Math.floor(number - 0) + '') + outputcents(number - 0);
        }
        //格式化金额
        var outputdollars = function (number) {
            if (number.length <= 3)
                return (number == '' ? '0' : number);
            else {
                var mod = number.length % 3;
                var output = (mod == 0 ? '' : (number.substring(0, mod)));
                for (i = 0; i < Math.floor(number.length / 3); i++) {
                    if ((mod == 0) && (i == 0))
                        output += number.substring(mod + 3 * i, mod + 3 * i + 3);
                    else
                        output += ',' + number.substring(mod + 3 * i, mod + 3 * i + 3);
                }
                return (output);
            }
        }
        var outputcents = function (amount) {
            amount = Math.round(((amount) - Math.floor(amount)) * 100);
            return (amount < 10 ? '.0' + amount : '.' + amount);
        }
        return outputmoney(strNum + "");
}

 

你可能感兴趣的:(正则,JavaScript,js,工具库)