標籤:
1.不能顯式地建立一個Math對象,直接使用它就可以了;
2.Math對象不能儲存資料,和String,Date對象不同;
3.前面知道了parseInt()函數會通過消去小數點後面的一切,來使一個小數變成整數(因此24.999變為24).經常我們需要更精確的計算。
於是通過Math對象的這幾個方法:
round():當小數是0.5或者大於0.5的時候,向上入一位;
ceil():始終向上舍入,因此23.75變成24,23.25也是如此;
floor():始終向下舍入,因此23.75變成23,23.25也是如此;
1 <DOCTYPE html> 2 <html> 3 <meta http-equiv="Content-Type" content="text/html;charset=utf-8"/> 4 <head> 5 <title>Math函數</title> 6 </head> 7 <script type="text/javascript"> 8 var userInput=prompt("請輸入一個數",""); 9 document.write("round()=",+Math.round(userInput));10 document.write("ceil()=",+Math.ceil(userInput));11 document.write("floor()=",+Math.floor(userInput));12 13 </script>14 <body>15 </body>16 </html>
4.可以使用Math對象的random()方法,產生一個大於等於0,但小於1的隨機小數。通常為了利用它,你需要再乘以某個數,然後在使用其中的一個舍入方法。
var diceThrow=Math.round(Math.random()*6)+1;
document.write("You threw a "+diceThrow);
javaScript一些函數--Math()