1. 程式人生 > >JavaScript Math物件 ceil()、floor()、round()方法

JavaScript Math物件 ceil()、floor()、round()方法

Math.ceil()
功能:對一個數進行上取整。
語法:Math.ceil(x)
引數:
x:一個數值。
返回值:返回大於或等於x,並且與之最接近的整數。
注:如果x是正數,則把小數“入”;如果x是負數,則把小數“舍”。
例:
<script type="text/javascript">
document.write( Math.ceil(1.2)+", "+Math.ceil(1.8)+", "+Math.ceil(-1.2)+", "+Math.ceil(-1.8) );
</script>
輸出結果為:
document.write( Math.ceil(1.2)+", "+Math.ceil(1.8)+", "+Math.ceil(-1.2)+", "+Math.ceil(-1.8) ); 2, 2, -1, -1


Math.floor()

功能:對一個數進行下取整。
語法:Math.floor(x)
引數:
x:一個數值。
返回值:返回小於或等於x,並且與之最接近的整數。
注:如果x是正數,則把小數“舍”;如果x是負數,則把小數“入”。
例:
<script type="text/javascript">
document.write( Math.floor(1.2)+", "+Math.floor(1.8)+", "+Math.floor(-1.2)+", "+Math.floor(-1.8) );
</script>
輸出結果為:
document.write( Math.floor(1.2)+", "+Math.floor(1.8)+", "+Math.floor(-1.2)+", "+Math.floor(-1.8) ); 1, 1, -2, -2


Math.round()
功能:四捨五入取整。
語法:Math.round(x)
引數:
x:一個數值。
返回值:與x最接近的整數。
例:
<script type="text/javascript">
document.write( Math.round(1.2)+", "+Math.round(1.8)+", "+Math.round(-1.2)+", "+Math.round(-1.8) );
</script>
輸出結果為:
document.write( Math.round(1.2)+", "+Math.round(1.8)+", "+Math.round(-1.2)+", "+Math.round(-1.8) ); 1, 2, -1, -2

說明

對於 0.5,該方法將進行上舍入。

例如,3.5 將舍入為 4,而 -3.5 將舍入為 -3。