Complete 2024 Web Development Bootcamp

Dr. Angela Yu

Back to JavaScript Index Page


JavaScript

Math.random() will return a 16 decimal place random number between 0 and 0.9999999999999999. This is a floating-point, pseudo-random number that is greater than or equal to 0 and less than 1, with approximately uniform distribution over that range.

So if we run Math.random(), we might get a number like 0.3485927615843259 which may not be particularly useful, depending on your application. Let's say we wanted to generate a random number for a roll of a dice. Well, a dice has six sides, so we would want to generate a random number between 1 and 6. So our random number generated by Math,random() is not going to be useful to us in it's current state. Let's fix that.

First we'll generate our initial random 16-digit decimal number between 0 and 0.9999999999999999

  • randNum = Math.random();

Next we multiply our random number by the maximum number we want. Since we want a random number between 1 and 6, we're going to multiply our random number by 6

  • randNum = randNum * 6;

Next we want to get rid of the decimal places, and turn our random number into a whole number. We accomplish this using Math.floor() which always rounds down, and returns the largest integer less than or equal to a given number.

  • randNum = Math.floor(randNum);

This will give us a random number between 0 and 5. It will not reach 6 because we never get a random number of 1. The closet we could get is 0.9999999999999999, and if we multiply this by 6, we get 5.9999999999999999. And when we convert this to a whole number, we get 5. Another problem is that Math.floor() will give us a number between 0 and 5. We want a number between 1 and 6 so all we need to do is to add 1 to our Math.floor() result.

  • randNum++;

and this will generate our dice roll with a random number between 1 and 6.

And lastly, we can combine this into one step formula, like so:

  • let randNum = Math.floor(Math.random() * 6) + 1;


Full Steps
  • JavaScript
    1. Math.random() - generate a random 16-digit decimal number between 0 and 0.9999999999999999.
    2. max-limit - multiply Math.random() by your maximum limit.
    3. Math.floor() - convert to whole number - rounds down, and returns the largest integer <= to a given number.
    4. add 1 - to get a random number between 1 and your max-limit.
  • JavaScript
  • condensed version
  • let variable = Math.floor(Math.random() * max-limit) + 1
Random Number Functions

If you're going to need multiple random numbers in your code, you may wish to incorporate a Random Number Function. There are two basic versions of the function:

and


Back to Top