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

输入:

10
1.7777777
9.1

输出:

10
1.78
9.1

如何在JavaScript中执行此操作?


当前回答

请参阅AmrAli的答案,以了解此解决方案的所有不同调整的更全面的运行和性能细分。

var DecimalPrecision=(函数){if(数字.EPSILON===未定义){Number.EPSILON=数学功率(2,-52);}if(Number.isInteger==未定义){Number.isInteger=函数(值){返回值类型==“number”&&isFinite(值)&&数学下限(值)==值;};}this.isRound=函数(n,p){设l=n.toString().split('.')[1].length;返回(p>=l);}this.round=函数(n,p=2){if(Number.isInteger(n)|| this.isRound(n,p))返回n;设r=0.5*Number.EPSILON*n;设o=1;而(p-->0)o*=10;如果(n<0)o*=-1;返回数学舍入((n+r)*o)/o;}this.ceil=函数(n,p=2){if(Number.isInteger(n)|| this.isRound(n,p))返回n;设r=0.5*Number.EPSILON*n;设o=1;而(p-->0)o*=10;返回Math.ceil((n+r)*o)/o;}this.flor=函数(n,p=2){if(Number.isInteger(n)|| this.isRound(n,p))返回n;设r=0.5*Number.EPSILON*n;设o=1;而(p-->0)o*=10;返回数学楼层((n+r)*o)/o;}返回此;})();console.log(DecimalPrecision.round(1.005));console.log(DecimalPrecision.ceil(1.005));console.log(DecimalPrecision.floor(1.005));console.log(DecimalPrecision.round(1.0049999));console.log(DecimalPrecision.ceil(1.0049999));console.log(DecimalPrecision.floor(1.0049999));console.log(DecimalPrecision.round(2.175495134384,7));console.log(DecimalPrecision.round(2.1753543549,8));console.log(DecimalPrecision.round(2.1755465135333,4));console.log(DecimalPrecision.ceil(17,4));console.log(DecimalPrecision.ceil(17.1,4));console.log(DecimalPrecision.ceil(17.1,15));

其他回答

只有在必要的时候你说?

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

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

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

对我来说,Math.rround()没有给出正确的答案。我发现Fixed(2)效果更好。以下是两者的示例:

console.log(数学舍入(43000/80000)*100);//错误的答案console.log(((43000/80000)*100).toFixed(2));//正确回答

避免舍入到任意位数的二进制问题的适当方法是:

function roundToDigits(number, digits) {
  return Number(Math.round(Number(number + 'e' + digits)) + 'e-' + digits);
}

修复toFixed()函数的一种方法是:

Number.prototype.toFixed = (prototype => {
    const toFixed = prototype.toFixed;

    // noinspection JSVoidFunctionReturnValueUsed
    return function (fractionDigits) {
        if (!fractionDigits) {
            return toFixed.call(this);
        } else {
            // Avoid binary rounding issues
            fractionDigits = Math.floor(fractionDigits);
            const n = Number(Math.round(Number(+this + 'e' + fractionDigits)) + 'e-' + fractionDigits);
            return toFixed.call(n, fractionDigits);
        }
    };
})(Number.prototype);

对这个答案稍作修改,似乎效果不错。

作用

function roundToStep(value, stepParam) {
   var step = stepParam || 1.0;
   var inv = 1.0 / step;
   return Math.round(value * inv) / inv;
}

用法

roundToStep(2.55) = 3
roundToStep(2.55, 0.1) = 2.6
roundToStep(2.55, 0.01) = 2.55

请参阅AmrAli的答案,以了解此解决方案的所有不同调整的更全面的运行和性能细分。

var DecimalPrecision=(函数){if(数字.EPSILON===未定义){Number.EPSILON=数学功率(2,-52);}if(Number.isInteger==未定义){Number.isInteger=函数(值){返回值类型==“number”&&isFinite(值)&&数学下限(值)==值;};}this.isRound=函数(n,p){设l=n.toString().split('.')[1].length;返回(p>=l);}this.round=函数(n,p=2){if(Number.isInteger(n)|| this.isRound(n,p))返回n;设r=0.5*Number.EPSILON*n;设o=1;而(p-->0)o*=10;如果(n<0)o*=-1;返回数学舍入((n+r)*o)/o;}this.ceil=函数(n,p=2){if(Number.isInteger(n)|| this.isRound(n,p))返回n;设r=0.5*Number.EPSILON*n;设o=1;而(p-->0)o*=10;返回Math.ceil((n+r)*o)/o;}this.flor=函数(n,p=2){if(Number.isInteger(n)|| this.isRound(n,p))返回n;设r=0.5*Number.EPSILON*n;设o=1;而(p-->0)o*=10;返回数学楼层((n+r)*o)/o;}返回此;})();console.log(DecimalPrecision.round(1.005));console.log(DecimalPrecision.ceil(1.005));console.log(DecimalPrecision.floor(1.005));console.log(DecimalPrecision.round(1.0049999));console.log(DecimalPrecision.ceil(1.0049999));console.log(DecimalPrecision.floor(1.0049999));console.log(DecimalPrecision.round(2.175495134384,7));console.log(DecimalPrecision.round(2.1753543549,8));console.log(DecimalPrecision.round(2.1755465135333,4));console.log(DecimalPrecision.ceil(17,4));console.log(DecimalPrecision.ceil(17.1,4));console.log(DecimalPrecision.ceil(17.1,15));