Javascript Math

Math is a built-in object that has properties and methods for mathematical constants and functions. It’s not a function object.

floor

Math.floor() function returns the largest integer less than or equal to a given number.

1
2
3
4
5
console.log(Math.floor(5.95));
// expected output: 5

console.log(Math.floor(5.05));
// expected output: 5

random

Math.random() returns a floating-point, pseudo-random number in the range 0 to less than 1 (inclusive of 0, but not 1). Example 0.9448960908626425

Using floor and random together:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
function getRandomInt(max) {
console.log('max = ' + max);
// max = 3

let random = Math.random();
console.log('Math.random() = ' + random);
// Math.random() = 0.9448960908626425

let randomTimesMax = random * max;
console.log('randomTimesMax = ' + randomTimesMax);
// randomTimesMax = 2.834688272587927

let mathFloor = Math.floor(randomTimesMax);
console.log('Math.floor(randomTimesMax) = ' + mathFloor);
// Math.floor(randomTimesMax) = 2
}

getRandomInt(3);