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

输入:

10
1.7777777
9.1

输出:

10
1.78
9.1

如何在JavaScript中执行此操作?


当前回答

它可能对你有用,

Math.round(num * 100)/100;

了解toFixed和round之间的区别。您可以查看Math.round(num)vs num.toFixed(0)和浏览器不一致性。

其他回答

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

作用

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

自从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>

您也可以重写Math.round函数来进行舍入校正,并为小数添加一个参数,并使用它,如:Math.round(Number,decimals)。请记住,这将覆盖内置组件Math.round,并为其提供另一个属性,而不是原始属性。

var round = Math.round;
Math.round = function (value, decimals) {
  decimals = decimals || 0;
  return Number(round(value + 'e' + decimals) + 'e-' + decimals);
}

然后你可以这样简单地使用它:

Math.round(1.005, 2);

https://jsfiddle.net/k5tpq3pd/3/

如果值是文本类型:

parseFloat("123.456").toFixed(2);

如果值是数字:

var numb = 123.23454;
numb = numb.toFixed(2);

有一个缺点,像1.5这样的值将给出“1.50”作为输出。@minitech建议的修复方法:

var numb = 1.5;
numb = +numb.toFixed(2);
// Note the plus sign that drops any "extra" zeroes at the end.
// It changes the result (which is a string) into a number again (think "0 + foo"),
// which means that it uses only as many digits as necessary.

Math.round似乎是一个更好的解决方案。但事实并非如此!在某些情况下,它不会正确舍入:

Math.round(1.005 * 100)/100 // Returns 1 instead of expected 1.01!

toFixed()在某些情况下也不会正确舍入(在Chrome v.55.0.2883.87中测试)!

示例:

parseFloat("1.555").toFixed(2); // Returns 1.55 instead of 1.56.
parseFloat("1.5550").toFixed(2); // Returns 1.55 instead of 1.56.
// However, it will return correct result if you round 1.5551.
parseFloat("1.5551").toFixed(2); // Returns 1.56 as expected.

1.3555.toFixed(3) // Returns 1.355 instead of expected 1.356.
// However, it will return correct result if you round 1.35551.
1.35551.toFixed(2); // Returns 1.36 as expected.

我想,这是因为1.555实际上就像是幕后的浮球1.55499994。

解决方案1是使用具有所需舍入算法的脚本,例如:

function roundNumber(num, scale) {
  if(!("" + num).includes("e")) {
    return +(Math.round(num + "e+" + scale)  + "e-" + scale);
  } else {
    var arr = ("" + num).split("e");
    var sig = ""
    if(+arr[1] + scale > 0) {
      sig = "+";
    }
    return +(Math.round(+arr[0] + "e" + sig + (+arr[1] + scale)) + "e-" + scale);
  }
}

它也在Plunker。

注意:这并不是每个人都能通用的解决方案。有几种不同的舍入算法。您的实现可能不同,这取决于您的需求。请参见舍入。

解决方案2是避免前端计算,并从后端服务器提取舍入值。

另一种可能的解决方案,也不是防弹的。

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

在某些情况下,当您舍入像1.3549999999999998这样的数字时,它将返回错误的结果。它应该是1.35,但结果是1.36。

如果使用的是Lodash库,可以使用Lodash的舍入方法,如下所示。

_.round(number, precision)

例如:

_.round(1.7777777, 2) = 1.78