Languages
[Edit]
EN

JavaScript Math.random() explain the difference between Math.ceil() vs Math.floor() vs Math.round()

17 points
Created by:
Zayyan-Todd
860

1. Random number

Edit

In JavaScript to generate a random number we use Math.random() and it returns numbers between 0 and 1.

2. Random number between 0 and 10 - floating point

Edit

If we want to get a random number between 0 and 10 we just need to multiply the result of Math.random() by 10 and round the result.

3. Random number between 0 and 10 - integer

Edit

Still, as we can see the numbers are floating-point and usually we want to have integers. The solution is pretty simple and now with help comes 3 methods how we can achieve it:

  • Math.round()
  • Math.floor()
  • Math.ceil()

4. Using Math.round()

Edit

Math.round() - round to the nearest number (integer e.g. 1,5,10)
e.g.:

  • 1.23 will be rounded to 1
  • 5.92 will be rounded to 6

Example how to generate a random number between 0 and 10 with Math.round().

5. Using Math.floor()

Edit

Math.floor() - round DOWN to the nearest number
e.g.:

  • 1.23 will be rounded to 1
  • 5.92 will be rounded to 5

Example how to generate random numbers between 0 and 10 with Math.floor().

6. Using Math.ceil()

Edit

Math.ceil() - round UP to the nearest number
e.g.:

  • 1.23 will be rounded to 2
  • 5.92 will be rounded to 6

Example how to generate random numbers between 0 and 10 with Math.ceil().

References

Edit
  1. Math.random method - Mozilla Docs
  2. Math.round method - Mozilla Docs
  3. Math.floor method - Mozilla Docs
  4. Math.ceil method - Mozilla Docs

Post thumbnail

Edit
JavaScript Math.random() explain the difference between Math.ceil() vs Math.floor() vs Math.round() - intro image
Intro image - Math.random()
1
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

JavaScript - math (popular problems)

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join