# 我如何在Javascript中舍入一个数字？

`math.round()`不起作用，因为它将其四舍五入到最接近的小数。

` `Math.floor()` `

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

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

`Math.floor()`可以工作，但与使用按位`OR`操作相比，它非常慢：

` `var rounded = 34.923 | 0; alert( rounded ); //alerts "34"` `

` `var a = []; var time = new Date().getTime(); for( i = 0; i < 100000; i++ ) { //a.push( Math.random() * 100000 | 0 ); a.push( Math.floor( Math.random() * 100000 ) ); } var elapsed = new Date().getTime() - time; alert( "elapsed time: " + elapsed );` `

` `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` `

` `rounded=Math.floor(number);` `

` `rounded=number|0;` `

` `if(number>0)rounded=Math.floor(number);else rounded=Math.ceil(number);` `

`number`舍入为`0`可以通过减去其有符号的小数部分`number % 1`

` `rounded = number - number % 1;` `

`Math.floor` （往`-Infinity`四舍五入）这个方法是非常准确的。

` `Math.floor(-0) => -0 -0 - -0 % 1 => +0 Math.floor(Infinity) => Infinity Infinity - Infinity % 1 => NaN Math.floor(-Infinity) => -Infinity -Infinity - -Infinity % 1 => NaN` `
` `Math.floor(1+7/8)` `

` `var dec = 12.3453465, int = dec >> 0; // returns 12` `

` `<script type="text/javascript"> function roundNumber(number, precision, isDown) { var factor = Math.pow(10, precision); var tempNumber = number * factor; var roundedTempNumber = 0; if (isDown) { tempNumber = -tempNumber; roundedTempNumber = Math.round(tempNumber) * -1; } else { roundedTempNumber = Math.round(tempNumber); } return roundedTempNumber / factor; } </script> <div class="col-sm-12"> <p>Round number 1.25 down: <script>document.write(roundNumber(1.25, 1, true));</script> </p> <p>Round number 1.25 up: <script>document.write(roundNumber(1.25, 1, false));</script></p> </div>` `