js中计算后结果如何保留小数点后N位

1、使用 Math.toFixed() 函数

1)方法介绍

toFixed() 方法可以将数字转换为字符串,并指定小数点后保留几位。如果小数实际位数不够指定的位数,不足的部分会补 0。所有主要浏览器都支持 toFixed() 方法。

toFixed() 使用的是银行家舍入规则:四舍六入五取偶(又称四舍六入五留双)

2)银行家舍入法:
四舍六入五考虑,五后非零就进一,五后为零看奇偶,五前为偶应舍去,五前为奇要进一

3)使用实例

 使用toFixed()函数,有可能会出现精度问题,可以考虑到用Math.round()函数

2、使用Math.round()函数

   //获取一个给定值和小数位数的值
   //value: 给定值,n :小数位数
   var NumRound = function (value, n) {
         //取某个数的平方,如: Math.pow(10,2):100
          return Math.round(value*Math.pow(10,n))/Math.pow(10,n);
   }

调用实例:

  console.log(NumRound(5/4,2));   //1.25
  console.log(NumRound(0.125,2));//0.13
  console.log(NumRound(5,2));   //5

当是整数时,没有在后面补零,如上面的5,返回还是5

3、使用自定义函数

     //获取一个给定值和小数位数的值,value: 给定值,n :小数位数
    var NumRoundtoFormat = function (x,n) {
                var f_x = parseFloat(x);
                if (isNaN(f_x)) {
                    alert("传递参数不是数字!");
                    return false;
                }
                var f_x = Math.round(x * Math.pow(10, n)) / Math.pow(10, n);
                var s_x = f_x.toString();
                var pos_decimal = s_x.indexOf('.');
                if (pos_decimal < 0) {
                    pos_decimal = s_x.length;
                    s_x += '.';
                }
                while (s_x.length <= pos_decimal + n) {
                    s_x += '0';
                }
                return s_x;
            }

调用实例:

   console.log(NumRoundtoFormat(3.1245,3));  //3.125
   console.log(NumRoundtoFormat(2.152,2));//2.15
   console.log(NumRoundtoFormat(6,2));  //6.00

参考网址:

https://www.cnblogs.com/NazLee/p/11646023.html

原文地址:https://www.cnblogs.com/xielong/p/12341598.html