Javascript Math ceil()、floor()、round()三個函數的區別

來源:互聯網
上載者:User

標籤:

Round是四捨五入的。。。Ceiling是向上取整。。float是向下取整 

下面來介紹將小數值舍入為整數的幾個方法:Math.ceil()、Math.floor()和Math.round()。 這三個方法分別遵循下列舍入規則:
◎Math.ceil()執行向上舍入,即它總是將數值向上舍入為最接近的整數;
◎Math.floor()執行向下舍入,即它總是將數值向下舍入為最接近的整數;
◎Math.round()執行標準舍入,即它總是將數值四捨五入為最接近的整數(這也是我們在數學課上學到的舍入規則)。

下面是使用這些方法的樣本:

對於所有介於25和26(不包括26)之間的數值,Math.ceil()始終返回26,因為它執行的是向上舍入。Math.round()方法只在數值大於等於25.5時返回26;否則返回25。最後,Math.floor()對所有介於25和26(不包括26)之間的數值都返回25。

以下是一些補充:
ceil():將小數部分一律向整數部分進位。
如:

 $(this).animate({left:"+=500px",height:"300px",opacity:"0.5"},3000)

 


Math.ceil(12.2)//返回13
Math.ceil(12.7)//返回13
Math.ceil(12.0)// 返回12

floor():一律捨去,僅保留整數。
如:

Math.floor(12.2)// 返回12
Math.floor(12.7)//返回12
Math.floor(12.0)//返回12

round():進行四捨五入
如:

Math.round(12.2)// 返回12
Math.round(12.7)//返回13
Math.round(12.0)//返回12

 $(this).animate({left:"+=500px",height:"300px",opacity:"0.5"},3000)

Javascript Math ceil()、floor()、round()三個函數的區別

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.