JavaScript Math.random() explain the difference between Math.ceil() vs Math.floor() vs Math.round()
1. Random number
In JavaScript to generate random number we use Math.random() and it returns number between 0 and 1.
// ONLINE-RUNNER:browser;
console.log(Math.random()); // 0.587777376294869
console.log(Math.random()); // 0.2197126264732836
console.log(Math.random()); // 0.9785932144070053
2. Random number between 0 and 10 - floating point
If we want to get random number between 0 and 10 we just need to multiply the result of Math.random() by 10 and round the result.
// ONLINE-RUNNER:browser;
console.log(Math.random() * 10); // 9.357923991790457
console.log(Math.random() * 10); // 3.5154493888867466
console.log(Math.random() * 10); // 5.1469888802577035
3. Random number between 0 and 10 - integer
Still as we can see the numbers are floating point and usually we want to have integers. Solution is pretty simple and now with help comes 3 methods how we can achieve it:
- Math.round()
- Math.floor()
- Math.ceil()
Below we have explanation points with code examples.
4. Using Math.round()
Math.round() - round to the nearest number (integer eg 1,5,10)
eg:
- 1.23 will be rounded to 1
- 5.92 will be rounded to 6
Example how to generate random number between 0 and 10 with Math.round()
// ONLINE-RUNNER:browser;
console.log(Math.round(1.23)); // 1
console.log(Math.round(5.92)); // 6
console.log(Math.round(Math.random() * 10)); // 2
console.log(Math.round(Math.random() * 10)); // 9
console.log(Math.round(Math.random() * 10)); // 5
5. Using Math.floor()
Math.floor() - round DOWN to the nearest number
eg:
- 1.23 will be rounded to 1
- 5.92 will be rounded to 5
Example how to generate random number between 0 and 10 with Math.floor()
// ONLINE-RUNNER:browser;
console.log(Math.floor(1.23)); // 1
console.log(Math.floor(5.92)); // 5
console.log(Math.floor(Math.random() * 10)); // 3
console.log(Math.floor(Math.random() * 10)); // 1
console.log(Math.floor(Math.random() * 10)); // 6
6. Using Math.ceil()
Math.ceil() - round UP to the nearest number
eg:
- 1.23 will be rounded to 2
- 5.92 will be rounded to 6
Example how to generate random number between 0 and 10 with Math.ceil()
// ONLINE-RUNNER:browser;
console.log(Math.ceil(1.23)); // 2
console.log(Math.ceil(5.92)); // 6
console.log(Math.ceil(Math.random() * 10)); // 5
console.log(Math.ceil(Math.random() * 10)); // 7
console.log(Math.ceil(Math.random() * 10)); // 3
References
- Math.random method - Mozilla Docs
- Math.round method - Mozilla Docs
- Math.floor method - Mozilla Docs
- Math.ceil method - Mozilla Docs
Post thumbnail
