Generate Random Whole Numbers within a Range logically working but functionnaly not working don't know why. Can someone explain why?

To create a random whole number within a range this piece of code works:

Math.floor(Math.random() * (max - min + 1)) + min

but I thought about it and logically this should work too:

Math.floor(Math.random() * (max - min) + min)

because if we put numbers in this it results in this:

Math.floor(0.999 * (90 - 30) + 30)

Math.floor(89,99999)

it results in 90 since Math.floor make it a whole number

which if we console.log should give us between 30 and 90 but in the curriculum it is written that it cannot go to the maximum. Is it because it just takes the whole number and not the closest whole number?

Hello!

It works as long as you don’t need an inclusive max.

The result of Math.floor(0.999 * (90 - 30) + 30) is 89, not 90, because Math.floor rounds down. If you wanted to round up, you would use Math.ceil and if you wanted to round to the nearest value, you use Math.round.

This is why a +1 is needed here: Math.floor(Math.random() * (max - min + 1)) + min.

Does it make sense :slight_smile:?

1 Like