round函數可以對數字取整,它是一個四捨五入函數,下面來看看round的文法:
1 Math.round(number)
下面來看幾個範例:
| 代碼如下 |
複製代碼 |
1 document.write (Math.round(2.65));// print 3 2 document.write (Math.round(7.05));// print 7 3 document.write (Math.round(-2.65));// print -3 4 document.write (Math.round(-8.15));// print -8 5 document.write (Math.round(11.65));// print 12
|
round函數的四捨五入只針對小數點後的第一位,如果要針對小數點後的其它位,我們可以先對數字乘以10的整數倍,round以後再除以同樣的數:
| 代碼如下 |
複製代碼 |
1 var my_val=11.257; 2 var my_val=11.254; 3 document.write (Math.round(my_val*100)/100); |
JavaScript round() 方法
定義和用法
round() 方法可把一個數字舍入為最接近的整數。
文法
Math.round(x)
傳回值
與 x 最接近的整數。
說明
對於 0.5,該方法將進行上舍入。
例如,3.5 將舍入為 4,而 -3.5 將舍入為 -3。
執行個體
把不同的數舍入為最接近的整數:
| 代碼如下 |
複製代碼 |
<script type="text/javascript"> document.write(Math.round(0.60) + "<br />") document.write(Math.round(0.50) + "<br />") document.write(Math.round(0.49) + "<br />") document.write(Math.round(-4.40) + "<br />") document.write(Math.round(-4.60)) </script> 輸出: 1 1 0 -4 -5 |
JavaScript Math.round() 函數
Math.round(x) -- 返回數字最接近的整數,四捨五入
round,中文"四捨五入"
round函數文法
Math.round(x);
x -- 為number類型的數字
round函數傳回值
返回x最接近的整數,如果x的小數部分大於等於0.5,傳回值是大於x的最小整數,否則round函數返回小於等於x的最大整數
round函數樣本
| 代碼如下 |
複製代碼 |
document.write(Math.round(5.8)); document.write(Math.round(5.2)); document.write(Math.round(-5.8)); document.write(Math.round(-5.2)); 結果: 6 5 -6 -5 |