【js】小数精度(去位取整和四舍五入)

来源:互联网 发布:瑞士胡椒盐包带淘宝 编辑:程序博客网 时间:2024/06/06 10:56
  1. 去位取整
    // 去位取小数    function decimalPlaces(num, decimal) {        var pow = Math.pow(10, decimal);        var res= parseInt(num*pow)/pow;        return res;    }

例:

decimalPlaces(1.5888888, 2)

返回 1.58

  1. 四舍五入
num.toFixed();

例:

num = 1.58888;num.toFixed(2);

返回 1.59