千分位数字格式化(用逗号隔开 代码已做了修改

最近做项目需要我们前端对金额进行千分位格式化(也就是说每三位用逗号隔开),代码已经做了修改  之前的版本是本人疏忽 真对不住大家了!现在已经做了修改 如果还有不完善的地方 请大家多多指教!

1. 支持用逗号隔开 0-9位 逗号隔开

JS代码如下:

复制代码 代码如下:


/**
         * JS格式化
         * @param number 要格式化的数字
         * @param d [0-9]位 逗号隔开
         */

         function numFormat(number,d) {

             var numArrs = ['0','1','2','3','4','5','6','7','8','9'],
                 REG_NUMBER = /^\d+(.\d+)?$/;

             d = d || 3; // 不传 是3位 千分位

if(isNumber(number) || isString(number) || REG_NUMBER.test(number)) {

// 先转换成字符串
                 var toString = number + '',
                     isPoint = toString.indexOf('.'),
                     prefix,   // 前缀
                     suffix,   // 后缀
                     t = '';

                 if(isPoint > 0) {
                    prefix = toString.substring(0,isPoint);
                    suffix = toString.substring(isPoint + 1);

}else if(isPoint == 0) {
                    prefix = '';
                    suffix = toString.substring(1);

}else {
                    prefix = toString;
                    suffix = '';
                 }

                 if(prefix != '') {
                    prefixArr = prefix.split('').reverse();

var isArrayIndex = isArray(d,numArrs);
                    if(isArrayIndex > -1) {

for(var i = 0, ilen = prefixArr.length; i < ilen; i+=1) {
                            t += prefixArr[i] + ((i + 1) % isArrayIndex == 0 && (i + 1) != prefixArr.length ? "," : "");
                        }
                        t = t.split("").reverse().join("");
                        if(suffix != '') {
                            return t + "." + suffix;
                        }else {
                            return t;
                        }

                    }else {
                        return '传入的多少位不正确';
                    }

                 }else if(prefix != '' && suffix == ''){

return prefix;

}else if(prefix == '' && suffix != ''){
                    prefix = 0;

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wdwjxp.html