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

输入:

10
1.7777777
9.1

输出:

10
1.78
9.1

如何在JavaScript中执行此操作?


当前回答

const formattedNumber=数学舍入(数字*100)/100;

其他回答

在Node.js环境中,我只使用roundTo模块:

const roundTo = require('round-to');
...
roundTo(123.4567, 2);

// 123.46

一个简单的解决方案是,如果你想四舍五入,可以使用Lodash的ceil函数。。。

_.round(6.001, 2)

给出6

_.ceil(6.001, 2);

给出6.01

_.ceil(37.4929, 2);

给出37.5

_.round(37.4929, 2);

给出37.49

根据评论中已给出的答案,链接至http://jsfiddle.net/AsRqx/,下面的一个对我来说很好。

function C(num)
{
    return +(Math.round(num + "e+2") + "e-2");
}

function N(num, places)
{
    return +(Math.round(num + "e+" + places) + "e-" + places);
}

C(1.005);

N(1.005, 0);
N(1.005, 1); // Up to 1 decimal places
N(1.005, 2); // Up to 2 decimal places
N(1.005, 3); // Up to 3 decimal places

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

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

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