我想最多四舍五入两位小数,但只有在必要时。

输入:

10
1.7777777
9.1

输出:

10
1.78
9.1

如何在JavaScript中执行此操作?


当前回答

有一种解决方案适用于所有数字。试试看。表达式如下所示。

Math.round((num + 0.00001) * 100) / 100. 

Try Below Ex:

Math.round((1.005 + 0.00001) * 100) / 100 
Math.round((1.0049 + 0.00001) * 100) / 100

我最近测试了所有可能的解决方案,并在尝试了近10次后最终得出了结果。

这是计算过程中出现的问题的屏幕截图,

.

转到金额字段。它几乎无限地回归。我尝试了toFixed()方法,但它在某些情况下不起作用(例如,尝试使用pi),最后导出了上面给出的解决方案。

其他回答

只有在必要的时候你说?

如果你也关心负数,我建议你。。。

有些答案对负数不太有效。。。

<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>roundPrecision</title>
    <script>
        class MyMath{
            static roundPrecision(number, precision, fillZeros) {
                // Number you want to round
                // precision nb of decimals
                // fillZeros the number of 0 You want to add IF necessary!
                // 0 = no fill with zeros.
                let num = number;
                let prec = precision;
                let exp = Math.pow(10, prec);
                let round = Math.round(number * exp)/exp
                if (fillZeros>0) {
                    return round.toFixed(fillZeros)
                }
                return round;
            }
        }
    </script>
</head>

<body>
    <p class="myMath" id="field1"></p>
    <p class="myMath" id="field2"></p>
    <p class="myMath" id="field3"></p>
    <p class="myMath" id="field4"></p>
    <p class="myMath" id="field5"></p>
    <p class="myMath" id="field6"></p>
    <p class="myMath" id="field7"></p>
    <script>
        document.getElementById("field1").innerHTML = MyMath.roundPrecision(5, 0, 3); // 5.000
        document.getElementById("field2").innerHTML = MyMath.roundPrecision(Math.PI, 2, 4); // 3.1400
        document.getElementById("field3").innerHTML = MyMath.roundPrecision(2.4, 1, 2); // 2.40
        document.getElementById("field4").innerHTML = MyMath.roundPrecision(2.9, 0, 2);   // 3.00
        document.getElementById("field5").innerHTML = MyMath.roundPrecision(10, 0, 2); // 10.00
        document.getElementById("field6").innerHTML = MyMath.roundPrecision(-10.5, 1, 2); // 10.00
        document.getElementById("field7").innerHTML = MyMath.roundPrecision(-1.006, 2, 0); // 10.00
    </script>
</body>
</html>

只有在必要时才能实现这种舍入的一种方法是使用Number.protype.toLocaleString():

myNumber.toLocaleString('en', {maximumFractionDigits:2, useGrouping:false})

这将提供您期望的输出,但是是字符串。如果不是您期望的数据类型,您仍然可以将它们转换回数字。

MarkG和Lavamantis提供了一个比已被接受的解决方案更好的解决方案。很遗憾他们没有得到更多的支持票!

这是我用来解决浮点小数问题的函数,也是基于MDN的。它甚至比Lavamantis的解决方案更通用(但不够简洁):

function round(value, exp) {
  if (typeof exp === 'undefined' || +exp === 0)
    return Math.round(value);

  value = +value;
  exp  = +exp;

  if (isNaN(value) || !(typeof exp === 'number' && exp % 1 === 0))
    return NaN;

  // Shift
  value = value.toString().split('e');
  value = Math.round(+(value[0] + 'e' + (value[1] ? (+value[1] + exp) : exp)));

  // Shift back
  value = value.toString().split('e');
  return +(value[0] + 'e' + (value[1] ? (+value[1] - exp) : -exp));
}

将其用于:

round(10.8034, 2);      // Returns 10.8
round(1.275, 2);        // Returns 1.28
round(1.27499, 2);      // Returns 1.27
round(1.2345678e+2, 2); // Returns 123.46

与拉瓦曼蒂斯的解决方案相比,我们可以做到。。。

round(1234.5678, -2); // Returns 1200
round("123.45");      // Returns 123

使用Math.rround():

Math.round(num * 100) / 100

或者更具体地说,为了确保1.005这样的数字正确,请使用Number.EPSILON:

Math.round((num + Number.EPSILON) * 100) / 100

我只是想根据前面提到的答案分享我的方法:

让我们创建一个函数,将任何给定的数值舍入到给定的小数位数:

function roundWDecimals(n, decimals) {
    if (!isNaN(parseFloat(n)) && isFinite(n)) {
        if (typeof(decimals) == typeof(undefined)) {
            decimals = 0;
        }
        var decimalPower = Math.pow(10, decimals);
        return Math.round(parseFloat(n) * decimalPower) / decimalPower;
    }
    return NaN;
}

并为数字原型引入一种新的“舍入”方法:

Object.defineProperty(Number.prototype, 'round', {
    enumerable: false,
    value: function(decimals) {
        return roundWDecimals(this, decimals);
    }
});

您可以测试它:

函数舍入WDecimals(n,小数){if(!isNaN(parseFloat(n))&&isFinite(n){if(typeof(小数)==typeof(未定义)){小数=0;}var decimalPower=数学.pow(10,小数);return Math.round(parseFloat(n)*decimalPower)/decimalPower;}返回NaN;}Object.defineProperty(Number.prototype,'round'{可枚举:false,值:函数(小数){返回舍入WDecimals(this,小数);}});var舍入=[{num:10,小数:2},{num:1.7777777,小数:2},{num:9.1,小数:2},{num:55.55,小数:1},{num:55.549,小数:1},{num:55,小数:0},{num:54.9,小数:0},{num:-55.55,小数:1},{num:-55.551,小数:1},{num:-55,小数:0},{num:1.005,小数:2},{num:1.005,小数:2},{num:198000000007,小数:2},],table='<table border=“1”><tr><th>Num</th><th>小数</th><th>结果</th></tr>';$.each(roundables,function(){表+='<tr>'+“<td>”+此.num+“</td>”+“<td>”+此小数+“</td>”+'<td>'+this.num.round(this.decimals)+'</td>'+'</tr>';});table+=“</table>”;$('.results').append(表);<script src=“https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js“></script><div class=“results”></div>