Lớp đối tượng Math hỗ trợ nhiều thuộc tính và phương thức giúp làm việc với các dữ liệu có kiểu là Number.

Constants

const PI = Math.PI
const E = Math.E
console.log(PI) // 3.141592653589793
console.log(E) // 2.718281828459045

Rounding

console.log(Math.round(PI)) // 3
console.log(Math.round(E)) // 3
console.log(Math.floor(PI)) // 3
console.log(Math.ceil(PI)) // 4

Minimum and Maximum

console.log(Math.min(-5, 3, 20, 4, 5, 10)) // -5, returns the minimum value
console.log(Math.max(-5, 3, 20, 4, 5, 10)) // 20, returns the maximum value

Random

Đoạn code bên dưới random một số từ 0 đến 10:

let randomNum = Math.random() // generates 0 to 0.999
 
let numBtnZeroAndTen = randomNum * 11
console.log(numBtnZeroAndTen) // this gives: min 0 and max 10.99
 
let randomNumRoundToFloor = Math.floor(numBtnZeroAndTen)
console.log(randomNumRoundToFloor) // this gives: between 0 and 10

Đoạn code rút gọn:

let randomNum = Math.floor(Math.random() * 11)
console.log(randomNum)