Javascript tutorial : why we add 1 to randomNumber variable?

in the javascript tutorial https://developer.mozilla.org/en-US/docs/Learn/JavaScript/First_steps/What_went_wrong, in the “Working through the logic” section it say that this line give us number between 0 and 99

let randomNumber = Math.floor(Math.random() * 100) ;

Hence us wanting to add 1, to give us a random number between 0 and 100:

let randomNumber = Math.floor(Math.random() * 100) + 1;

but what if the generated random number is ‘0.10055555555’ for example,
the second line will give us 101 wheres the first line will output 100 ?!

It doesn’t though — it says that this line gives us a number between 0 and 99. This is because Math.floor() rounds the result of what’s inside it down to the nearest whole number.

Hence wanting to add 1, to make the random number between 1 and 100, not 0 and 99.

2 Likes

My bad, yes the lowest number 0 not 1, but still my problem with max number you will get!

If the generated number is “0.10055555555”, then without adding 1 you will get 100.

I think the confusion here is coming from the order in which the calculation is done on the line. Let’s look at it again:

let randomNumber = Math.floor(Math.random() * 100) + 1;
  1. First of all, Math.random() is run, which generates a random number between 0 and 1. It is never 1 — it is actually between 0 and just below 1 (see the Math.random() reference page).
  2. Then we multiply that random number by 100.
  3. Then we run Math.floor() on the result of the above calculation, to round the result down to the nearest integer. If the original random number was 0, then this would equal 0, as 0 * 100 is 0. If the random number was 0.999999999, then this would equal 99. 99.9999999 rounded down is 99.
  4. We add 1 to the result of the above. Meaning that the final result is between 1 and 100.
2 Likes

thank you @chrisdavidmills