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

输入:

10
1.7777777
9.1

输出:

10
1.78
9.1

如何在JavaScript中执行此操作?


当前回答

下面是一个原型方法:

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

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

其他回答

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

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

这适用于以下两个示例:

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

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

使用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)和浏览器不一致性

数学基础和圆定义:

带我们去

让舍入=x=>(x+0.05-(x+0.05)%0.01+'')。替换(/(\…)(.*)/,'1');//对于像1.384这样的情况,我们需要使用正则表达式来获取点后的2位数字//和切断机器误差(epsilon)console.log(圆形(10));控制台日志(圆形(1.777777));console.log(圆形(1.7747777));console.log(圆形(1.384));

使用此函数Number(x).toFixed(2);