JS之向上取整、向下取整、四舍五入等

  • 只保留整數(shù)部分(丟棄小數(shù)部分)
parseInt(5.1234);      // 5
  • 向下取整(<= 該數(shù)值的最大整數(shù),和parseInt()一樣)
Math.floor(5.1234);     // 5    
  • 向上取整(有小數(shù),整數(shù)部分就+1)
Math.ceil(5.1234);     // 6
  • 四舍五入(小數(shù)部分)
Math.round(5.1234);      // 5
Math.round(5.6789);     // 6
  • 取絕對值
Math.abs(-1);      // 1
  • 返回兩數(shù)中的較大者
Math.max(1,2);     // 2
  • 返回兩數(shù)中的較小者
Math.min(1,2);    // 1
  • 隨機數(shù)(0-1)
Math.random();  //返回 0(包括) 至 1(不包括) 之間的隨機數(shù)
JavaScript 隨機整數(shù)

Math.random() 與 Math.floor() 一起使用用于返回隨機整數(shù)。
Math.floor(Math.random() * 10); // 返回 0 至 9 之間的數(shù)
Math.floor(Math.random() * 11); // 返回 0 至 10 之間的數(shù)
Math.floor(Math.random() * 100); // 返回 0 至 99 之間的數(shù)
Math.floor(Math.random() * 101); // 返回 0 至 100 之間的數(shù)
Math.floor(Math.random() * 10) + 1; // 返回 1 至 10 之間的數(shù)
Math.floor(Math.random() * 100) + 1; // 返回 1 至 100 之間的數(shù)

一個適當?shù)碾S機函數(shù)
正如你從上面的例子看到的,創(chuàng)建一個隨機函數(shù)用于生成所有隨機整數(shù)是一個好主意。

這個 JavaScript 函數(shù)始終返回介于 min(包括)和 max(不包括)之間的隨機數(shù):

function getRndInteger(min, max) {
    return Math.floor(Math.random() * (max - min) ) + min;
}

這個 JavaScript 函數(shù)始終返回介于 min 和 max(都包括)之間的隨機數(shù):

function getRndInteger(min, max) {
    return Math.floor(Math.random() * (max - min + 1) ) + min;
}

原文:http://www.itdecent.cn/p/a93bd02d9eb7

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容