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

输入:

10
1.7777777
9.1

输出:

10
1.78
9.1

如何在JavaScript中执行此操作?


当前回答

具有可读选项的函数更直观:

function round_number(options) {
    const places = 10**options.decimal_places;
    const res = Math.round(options.number * places)/places;
    return(res)
}

用法:

round_number({
    number : 0.5555555555555556,
    decimal_places : 3
})

0.556

其他回答

使用Math.rround():

Math.round(num * 100) / 100

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

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

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

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

// 123.46

使用类似的方法“parseFloat(parseFlat(value).toFixed(2))”

parseFloat(parseFloat("1.7777777").toFixed(2))-->1.78 
parseFloat(parseFloat("10").toFixed(2))-->10 
parseFloat(parseFloat("9.1").toFixed(2))-->9.1

我仍然不认为有人给他答案,告诉他如何在需要时只进行舍入。我认为最简单的方法是检查数字中是否有小数,如下所示:

var num = 3.21;
if ( (num+"").indexOf('.') >= 0 ) { //at least assert to string first...
    // whatever code you decide to use to round
}

这个函数对我有用。你只需输入数字和你想要舍入的位置,它就可以轻松地完成所需的操作。

round(source, n) {
  let places = Math.pow(10, n);

  return Math.round(source * places) / places;
}