当前位置:编程学习 > JS >>

js 数字添加逗号,格式化数字

 
      function addCommas(nStr)  
        {  
            nStr += '';  
            x = nStr.split('.');  
            x1 = x[0];  
            x2 = x.length > 1 ? '.' + x[1] : '';  
            var rgx = /(\d+)(\d{3})/;  
            while (rgx.test(x1)) {  
                x1 = x1.replace(rgx, '$1' + ',' + '$2');  
            }  
            return x1 + x2;  
        }  
   
//数字格式化就可以变成   
      var num = 123456.4231;  
          num = num.toFixed(2);  
          num =addCommas(num);  
//     num = 123456.42  

      function addCommas(nStr)
        {
            nStr += '';
            x = nStr.split('.');
            x1 = x[0];
            x2 = x.length > 1 ? '.' + x[1] : '';
            var rgx = /(\d+)(\d{3})/;
            while (rgx.test(x1)) {
                x1 = x1.replace(rgx, '$1' + ',' + '$2');
            }
            return x1 + x2;
        }
 
//数字格式化就可以变成
      var num = 123456.4231;
          num = num.toFixed(2);
          num =addCommas(num);
//     num = 123456.42

 

补充:web前端 , JavaScript ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,