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


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

Math.random() 與 Math.floor() 一起使用用於返回隨機整數。

Math.floor(Math.random() * 10);		// 返回 0 至 9 之間的數 
Math.floor(Math.random() * 11);		// 返回 0 至 10 之間的數
Math.floor(Math.random() * 100);	// 返回 0 至 99 之間的數
Math.floor(Math.random() * 101);	// 返回 0 至 100 之間的數
Math.floor(Math.random() * 10) + 1;	// 返回 1 至 10 之間的數
Math.floor(Math.random() * 100) + 1;	// 返回 1 至 100 之間的數

一個適當的隨機函數
正如你從上面的例子看到的,創建一個隨機函數用於生成所有隨機整數是一個好主意。

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

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

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

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

原文:https://www.jianshu.com/p/a93bd02d9eb7


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM