Generate Random Whole Numbers with JavaScript (mathematics)

Tell us what’s happening:

I passed the challenge but I don’t understand the maths behind the exercise - especially regarding taking the randomly generated decimals and then multiplying them 10 in this case.

Your code so far

var randomNumberBetween0and19 = Math.floor(Math.random() * 20);

function randomWholeNum() {

  // Only change code below this line.

  return Math.floor(Math.random() * 10);
}

Link to the challenge:

2 Likes

Math.random() generates a “random” number between 0 and 1 (e.g. 0.4254513341295314). Since you want a number between 0 and 9 (10 possibilities) you multiply this by 10. This gives you a number between 0 and 9 (e.g. 4.254513341295314), but you want an integer, so you use Math.floor() to round it down to the nearest integer (e.g. 4).

4 Likes