js格式化数字和金额

格式化数字,格式化金额:

 1 function number_format(number, decimals, dec_point, thousands_sep) {
 2     /*
 3     * 参数说明:
 4     * number:要格式化的数字
 5     * decimals:保留几位小数
 6     * dec_point:小数点符号
 7     * thousands_sep:千分位符号
 8     * */
 9     number = (number + '').replace(/[^0-9+-Ee.]/g, '');
10     var n = !isFinite(+number) ? 0 : +number,
11         prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),
12         sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep,
13         dec = (typeof dec_point === 'undefined') ? '.' : dec_point,
14         s = '',
15         toFixedFix = function (n, prec) {
16             var k = Math.pow(10, prec);
17             return '' + Math.ceil(n * k) / k;
18         };
19  
20     s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.');
21     var re = /(-?\d+)(\d{3})/;
22     while (re.test(s[0])) {
23         s[0] = s[0].replace(re, "$1" + sep + "$2");
24     }
25  
26     if ((s[1] || '').length < prec) {
27         s[1] = s[1] || '';
28         s[1] += new Array(prec - s[1].length + 1).join('0');
29     }
30     return s.join(dec);
31 }

  

如何使用:

1   var num=number_format(1234567.089, 2, ".", ",");//1,234,567.09

 

 

再来一个,直接舍去的办法:

    

 1 function number_format(number, decimals, dec_point, thousands_sep) {
 2         /*
 3         * 参数说明:
 4         * number:要格式化的数字
 5         * decimals:保留几位小数
 6         * dec_point:小数点符号
 7         * thousands_sep:千分位符号
 8         * */
 9         number = (number + '').replace(/[^0-9+-Ee.]/g, '');
10         var n = !isFinite(+number) ? 0 : +number,
11  
12             prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),
13             sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep,
14             dec = (typeof dec_point === 'undefined') ? '.' : dec_point,
15             s = '',
16             toFixedFix = function (n, prec) {
17                 var k = Math.pow(10, prec);
18                 return '' + Math.floor(n * k) / k;
19             };
20         s = (prec ? toFixedFix(n, prec) : '' + Math.floor(n)).split('.');
21         var re = /(-?\d+)(\d{3})/;
22         console.log(s)
23         while (re.test(s[0])) {
24             s[0] = s[0].replace(re, "$1" + sep + "$2");
25         }
26  
27         if ((s[1] || '').length < prec) {
28             s[1] = s[1] || '';
29             s[1] += new Array(prec - s[1].length + 1).join('0');
30         }
31         return s.join(dec);
32     }
33     number_format(1234567.089, 2, ".", ",");//1,234,567.08

 

      

 

 

posted @ 2016-09-06 15:13  方小川  阅读(39040)  评论(0编辑  收藏  举报