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

输入:

10
1.7777777
9.1

输出:

10
1.78
9.1

如何在JavaScript中执行此操作?


当前回答

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');
  });
})

其他回答

我在MDN上找到了这个。他们的方法避免了前面提到的1.005的问题。

函数roundToTwo(num){return+(数学舍入(num+“e+2”)+“e-2”);}console.log(“1.005=>”,roundToTwo(1.005));console.log('10=>',roundToTwo(10));console.log('1.7777777=>',roundToTwo(1.7777777));console.log('9.1=>',roundToTwo(9.1));console.log('1234.5678=>',roundToTwo(1234.5678));

使用Math.rround():

Math.round(num * 100) / 100

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

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

自从ES6以来,有一种“正确”的方法(不覆盖静态数据和创建变通方法)可以通过使用toPrecision来实现这一点

变量x=1.49999999999;console.log(x.toPrecision(4));console.log(x.toPrecision(3));console.log(x.toPrecision(2));var y=数学PI;console.log(y.toPrecision(6));console.log(y.toPrecision(5));console.log(y.toPrecision(4));变量z=222.987654console.log(z.toPrecision(6));console.log(z-toPrecision(5));console.log(z-toPrecision(4));

然后你可以解析Float,零将“消失”。

console.log(parseFloat((1.4999).toPrecision(3)));console.log(parseFloat((1.005).toPrecision(3)));console.log(parseFloat((1.0051).toPrecision(3)));

但它并不能解决“1.005舍入问题”,因为它是浮点分数处理过程中的固有问题。

控制台日志(1.005-0.005);

如果您对库开放,可以使用bignumber.js

控制台日志(1.005-0.005);console.log(新BigNumber(1.005).减(0.005));console.log(新BigNumber(1.005).round(4));console.log(新BigNumber(1.005).round(3));console.log(新BigNumber(1.005).round(2));console.log(新BigNumber(1.005).rround(1));<script src=“https://cdnjs.cloudflare.com/ajax/libs/bignumber.js/2.3.0/bignumber.min.js“></script>

这是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;
}

一个助手函数,其中rounding是默认舍入:

let rounding = 4;

let round = (number) => { let multiply = Math.pow(10,rounding);  return Math.round(number*multiply)/multiply};

console.log(round(0.040579431));

=> 0.0406