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

输入:

10
1.7777777
9.1

输出:

10
1.78
9.1

如何在JavaScript中执行此操作?


当前回答

根据所选答案和对同一问题的投票意见:

Math.round((num + 0.00001) * 100) / 100

这适用于以下两个示例:

Math.round((1.005 + 0.00001) * 100) / 100

Math.round((1.0049 + 0.00001) * 100) / 100

其他回答

MarkG和Lavamantis提供了一个比已被接受的解决方案更好的解决方案。很遗憾他们没有得到更多的支持票!

这是我用来解决浮点小数问题的函数,也是基于MDN的。它甚至比Lavamantis的解决方案更通用(但不够简洁):

function round(value, exp) {
  if (typeof exp === 'undefined' || +exp === 0)
    return Math.round(value);

  value = +value;
  exp  = +exp;

  if (isNaN(value) || !(typeof exp === 'number' && exp % 1 === 0))
    return NaN;

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

  // Shift back
  value = value.toString().split('e');
  return +(value[0] + 'e' + (value[1] ? (+value[1] - exp) : -exp));
}

将其用于:

round(10.8034, 2);      // Returns 10.8
round(1.275, 2);        // Returns 1.28
round(1.27499, 2);      // Returns 1.27
round(1.2345678e+2, 2); // Returns 123.46

与拉瓦曼蒂斯的解决方案相比,我们可以做到。。。

round(1234.5678, -2); // Returns 1200
round("123.45");      // Returns 123

使用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

可以使用.toFixed(小数位数)。

var str = 10.234.toFixed(2); // => '10.23'
var number = Number(str); // => 10.23

使用类似的方法“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