Math.floor(x)
其中參數 x 是必需的,可以是任意數值或表達式。方法執行後返回的是「小於等於 x,且與 x 最接近的整數」。
floor() 方法可對一個數進行下捨入,也就是向下取整。它返回小於或等於參數、並與之最接近的整數。值得注意的是,對於負數,它是往「更小的方向」取整,例如 Math.floor(-5.1) 得到 -6。
<script type="text/javascript"> document.write(Math.floor(0.60) + "<br />") // 0 document.write(Math.floor(0.40) + "<br />") // 0 document.write(Math.floor(5) + "<br />") // 5 document.write(Math.floor(5.1) + "<br />") // 5 document.write(Math.floor(-5.1) + "<br />") // -6 document.write(Math.floor(-5.9)) // -6 </script>
預期輸出:
0 0 5 5 -6 -6
Math.floor 常用於數值取整、生成隨機整數等場景,是日常開發中不可或缺的工具方法。