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

输入:

10
1.7777777
9.1

输出:

10
1.78
9.1

如何在JavaScript中执行此操作?


当前回答

一个简单的解决方案是,如果你想四舍五入,可以使用Lodash的ceil函数。。。

_.round(6.001, 2)

给出6

_.ceil(6.001, 2);

给出6.01

_.ceil(37.4929, 2);

给出37.5

_.round(37.4929, 2);

给出37.49

其他回答

这对正数、负数和大数都适用:

function Round(value) {
    const neat = +(Math.abs(value).toPrecision(15));
    const rounded = Math.round(neat * 100) / 100;

    return rounded * Math.sign(value);
}

//0.244 -> 0.24
//0.245 -> 0.25
//0.246 -> 0.25

//-0.244 -> -0.24
//-0.245 -> -0.25
//-0.246 -> -0.25

我在MDN上找到了这个。他们的方法避免了前面提到的1.005的问题。

函数roundToTwo(num){return+(数学舍入(num+“e+2”)+“e-2”);}console.log(“1.005=>”,roundToTwo(1.005));console.log('10=>',roundToTwo(10));console.log('1.7777777=>',roundToTwo(1.7777777));console.log('9.1=>',roundToTwo(9.1));console.log('1234.5678=>',roundToTwo(1234.5678));

number=(parseInt((number +0.005)*100))/100;     

如果要正常舍入(2位小数),请添加0.005

8.123 +0.005=> 8.128*100=>812/100=>8.12   

8.126 +0.005=> 8.131*100=>813/100=>8.13   

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

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

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

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

// 123.46