js四舍五入保留2位小数

 

 

 

function fomatFloat(num,n){   
    var f = parseFloat(num);
    if(isNaN(f)){
        return false;
    }   
    f = Math.round(f*Math.pow(10, n))/Math.pow(10, n); // n 幂   
    var s = f.toString();
    var rs = s.indexOf('.');
    //判定如果是整数,增加小数点再补0
    if(rs < 0){
        rs = s.length;
        s += '.'; 
    }
    while(s.length <= rs + n){
        s += '0';
    }
    return s; 
  }
  console.log(fomatFloat('123214',2));// 123214
  console.log(fomatFloat('123214.345',2));//123214.35
  console.log(fomatFloat('123214.344',2));//123214.34

posted @ 2021-07-15 17:13  古墩古墩  Views(219)  Comments(0Edit  收藏  举报