Who can explain it for me?

Сonsole.log(Math.floor(Math.random() * 100));
Why the answer is 4?
Math floor we are using to be sure that number will not be decemical, math random it will be a figure beetwe 0 and 1 after we multiply by 100, but how we received - 4 as an answer?

Hi,
Math.random() generates a random floating point number between 0 and, up to but not including, 1.
e.g. 0.04837261…
Then it gets multiplied by 100 (this means our random range is now effectively between 0 and, up to but not including 100)
e.g. 4.837261…
Finally, Math.floor changes the floating point number into an integer by rounding it down to the nearest whole number (i.e. disregarding the decimal section of the number)
e.g. 4 (the .837261 is disregarded)

Hope that helps

3 Likes

Thank you so much, it was really helpful.

We need to generate a random number between 0 and 7.
How we know that to receive 7 we have to use multiply 8, please explain for me too. I dont get it.
let randomNumber = Math.random()*8

Math.random picks a number between 0 and 0.999999…
It will never pick 1, so the most
Math.random() * 8
can be is 7.999…
If this is then fed in to Math.floor to remove the decimal part then the output is going to be 7 at the most.

ie, Math.random() * 8 means pick a random number between 0 and 8, but not including 8.

hope that helps

5 Likes