Javascript Math ceil()、floor()、round()三個函數(shù)的區(qū)別
下面來介紹將小數(shù)值舍入為整數(shù)的幾個方法:Math.ceil()、Math.floor()和Math.round()。 這三個方法分別遵循下列舍入規(guī)則:
◎Math.ceil()執(zhí)行向上舍入,即它總是將數(shù)值向上舍入為最接近的整數(shù);
◎Math.floor()執(zhí)行向下舍入,即它總是將數(shù)值向下舍入為最接近的整數(shù);
◎Math.round()執(zhí)行標準舍入,即它總是將數(shù)值四舍五入為最接近的整數(shù)(這也是我們在數(shù)學課上學到的舍入規(guī)則)。
下面是使用這些方法的示例:
alert(Math.ceil(25.9)); //26 alert(Math.ceil(25.5)); //26 alert(Math.ceil(25.1)); //26 alert(Math.round(25.9)); //26 alert(Math.round(25.5)); //26 alert(Math.round(25.1)); //25 alert(Math.floor(25.9)); //25 alert(Math.floor(25.5)); //25 alert(Math.floor(25.1)); //25
南昌網(wǎng)絡公司技術人員總結:對于所有介于25和26(不包括26)之間的數(shù)值,Math.ceil()始終返回26,因為它執(zhí)行的是向上舍入。Math.round()方法只在數(shù)值大于等于25.5時返回26;否則返回25。最后,Math.floor()對所有介于25和26(不包括26)之間的數(shù)值都返回25。
以下是一些補充:
ceil():將小數(shù)部分一律向整數(shù)部分進位。
如:
Math.ceil(12.2)//返回13
Math.ceil(12.7)//返回13
Math.ceil(12.0)// 返回12
floor():一律舍去,僅保留整數(shù)。
如:
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
- 輕松掌握JavaScript中的Math object數(shù)學對象
- 使用js Math.random()函數(shù)生成n到m間的隨機數(shù)字
- JavaScript Math.ceil 方法(對數(shù)值向上取整)
- JavaScript Math.floor方法(對數(shù)值向下取整)
- js中Math之random,round,ceil,floor的用法總結
- 介紹JavaScript中Math.abs()方法的使用
- JavaScript中使用Math.PI圓周率屬性的方法
- js Math 對象的方法
- JavaScript中使用指數(shù)方法Math.exp()的簡介
- js中常用的Math方法總結
- JavaScript使用math.js進行精確計算操作示例
- js Math數(shù)學簡單使用操作示例
相關文章
Javascript 動態(tài)改變imput type屬性
這篇文章主要介紹了Javascript 動態(tài)改變imput type屬性的相關資料,并附簡單實例代碼,需要的朋友可以參考下2016-11-11javascript、php關鍵字搜索函數(shù)的使用方法
這篇文章主要介紹了javascript、php關鍵字搜索函數(shù)的使用方法的相關資料,需要的朋友可以參考下2018-05-05JavaScript學習筆記整理_setTimeout的應用
下面小編就為大家?guī)硪黄狫avaScript學習筆記整理_setTimeout的應用。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2016-09-09在Javascript中處理數(shù)組之toSource()方法的使用
這篇文章主要介紹了在Javascript中處理數(shù)組之toSource()方法的使用,是JS入門學習中的基礎知識,需要的朋友可以參考下2015-06-06