js中控制小数位数

来源:互联网 发布:淘宝买冰箱靠谱吗 编辑:程序博客网 时间:2024/05/01 22:29
  1. 保留小数位数 
    • Math.round(x*100)/100 
      将浮点数四舍五入,取小数点后2位
      可以实现保留两位小数
    • 强制保留两位小数  
                         
            function toDecimal2(x ) { 
            var f = parseFloat(x); 
            if (isNaN(f)) { 
                return false; 
            } 
            var f = Math.round(x*100 )/100 ; 
             var s = f.toString(); 
             var rs = s.indexOf('.' ); 
            if (rs < 0) { 
                 rs = s.length; 
                 s += '.'; 
            } 
             while (s.length <= rs + 2) { 
                 s += '0'; 
            } 
            return s; 
             } 
         
           function fomatFloat( src,pos ){    
             return Math.round(src* Math.pow(10, pos))/Math.pow(10 , pos);    
             }
 
  1.  Math.ceil()向上取整
  2.  Math.floor()向上取整
  3. Math.round()四舍五入取整
  4. parseInt(x)直接取整
  5. X.toFixed(n);保留n位小数

  1. Math.power()n次方
文章转载自:http://m.cnblogs.com/288851/5560819.html

0 0
原创粉丝点击