DIV CSS 佈局教程網

JavaScript Math.floor() 方法:向下取整的用法與範例
編輯:關於JavaScript     

語法

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 常用於數值取整、生成隨機整數等場景,是日常開發中不可或缺的工具方法。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved