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

输入:

10
1.7777777
9.1

输出:

10
1.78
9.1

如何在JavaScript中执行此操作?


当前回答

只有在必要的时候你说?

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

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

<!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>

其他回答

MarkG的答案是正确的。这里是任何小数位数的通用扩展。

Number.prototype.round = function(places) {
  return +(Math.round(this + "e+" + places)  + "e-" + places);
}

用法:

var n = 1.7777;    
n.round(2); // 1.78

单元测试:

it.only('should round floats to 2 places', function() {
    
  var cases = [
    { n: 10,      e: 10,    p:2 },
    { n: 1.7777,  e: 1.78,  p:2 },
    { n: 1.005,   e: 1.01,  p:2 },
    { n: 1.005,   e: 1,     p:0 },
    { n: 1.77777, e: 1.8,   p:1 }
  ]
    
  cases.forEach(function(testCase) {
    var r = testCase.n.round(testCase.p);
    assert.equal(r, testCase.e, 'didn\'t get right number');
  });
})

如果您碰巧已经在使用D3.js库,那么他们有一个强大的数字格式库。

舍入具体为D3舍入。

在您的案例中,答案是:

> d3.round(1.777777, 2)
1.78

> d3.round(1.7, 2)
1.7

> d3.round(1, 2)
1

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

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),最后导出了上面给出的解决方案。

我发现这适用于我的所有用例:

const round = (value, decimalPlaces = 0) => {
    const multiplier = Math.pow(10, decimalPlaces);
    return Math.round(value * multiplier + Number.EPSILON) / multiplier;
};

记住这是ES6。ES5的等效版本很容易编写,所以我不打算添加它。

这是astorije的答案的修改版本,更好地支持负值舍入。

// https://stackoverflow.com/a/21323513/384884
// Modified answer from astorije
function round(value, precision) {
    // Ensure precision exists
    if (typeof precision === "undefined" || +precision === 0) {
        // Just do a regular Math.round
        return Math.round(value);
    }

    // Convert the value and precision variables both to numbers
    value = +value;
    precision = +precision;

    // Ensure the value is a number and that precision is usable
    if (isNaN(value) || !(typeof precision === "number" && precision % 1 === 0)) {
        // Return NaN
        return NaN;
    }

    // Get the sign of value
    var signValue = Math.sign(value);

    // Get the absolute value of value
    value = Math.abs(value);

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

    // Shift back
    value = value.toString().split("e");
    value = +(value[0] + "e" + (value[1] ? (+value[1] - precision) : -precision));

    // Apply the sign
    value = value * signValue;

    // Return rounded value
    return value;
}