如何在JavaScript中四舍五入一个数字?

Math.round()不起作用,因为它舍入到最接近的小数。

我不确定是否有更好的方法,而不是在小数点处分开,保留第一位。一定有……


当前回答

朝向负无穷- Math.floor()

+3.5 => +3.0
-3.5 => -4.0

可以使用Math.trunc()向零舍入。旧的浏览器不支持此功能。如果需要支持这些,可以使用Math.ceil()表示负数,使用Math.floor()表示正数。

+3.5 => +3.0 using Math.floor()
-3.5 => -3.0 using Math.ceil()

其他回答

Math.floor(1+7/8)

朝向负无穷- Math.floor()

+3.5 => +3.0
-3.5 => -4.0

可以使用Math.trunc()向零舍入。旧的浏览器不支持此功能。如果需要支持这些,可以使用Math.ceil()表示负数,使用Math.floor()表示正数。

+3.5 => +3.0 using Math.floor()
-3.5 => -3.0 using Math.ceil()
Math.round(3.14159 * 100) / 100  // 3.14

3.14159.toFixed(2);              // 3.14 returns a string
parseFloat(3.14159.toFixed(2));  // 3.14 returns a number

Math.round(3.14159)  // 3
Math.round(3.5)      // 4
Math.floor(3.8)      // 3
Math.ceil(3.2)       // 4

如果需要四舍五入到特定的小数点后数位,可以尝试使用此函数

function roundDown(number, decimals) {
    decimals = decimals || 0;
    return ( Math.floor( number * Math.pow(10, decimals) ) / Math.pow(10, decimals) );
}

例子

alert(roundDown(999.999999)); // 999
alert(roundDown(999.999999, 3)); // 999.999
alert(roundDown(999.999999, -1)); // 990

这是我发现的最可靠的解决方案。

function round(value, decimals) {
    return Number(Math.floor(parseFloat(value + 'e' + decimals)) + 'e-' + decimals);
 }

来源:Jack L Moore的博客