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

输入:

10
1.7777777
9.1

输出:

10
1.78
9.1

如何在JavaScript中执行此操作?


当前回答

+(10).toFixed(2); // = 10
+(10.12345).toFixed(2); // = 10.12

(10).toFixed(2); // = 10.00
(10.12345).toFixed(2); // = 10.12

其他回答

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

作用

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

下面是一个原型方法:

Number.prototype.round = function(places){
    places = Math.pow(10, places); 
    return Math.round(this * places)/places;
}

var yournum = 10.55555;
yournum = yournum.round(2);

要不处理许多0,请使用以下变体:

Math.round(num * 1e2) / 1e2

使用Math.rround():

Math.round(num * 100) / 100

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

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

这可能会帮助您:

var result = Math.round(input*100)/100;

有关更多信息,您可以查看Math.round(num)vs num.toFixed(0)和浏览器不一致性