JS tip - How to generate Random number within a given Range

← PrevNext →

The Math.random() method in JavaScript will generate a random number between 0 and 1. However, the formula to get a random number between a given range is slightly different.

First lets check the Math.random() function.

<script>
  document.write (Math.random());  // Output: a random value between 0 and 1, such as, 0.7633
</script>
Try it

To generate a random number between 0 and 10, you can use this formula.

<script>
  document.write (Math.random() * 10);  // Output: a random value like 4.805398688602722
</script>
Try it

Now let us assume, I want to generate a random number between the range 5 and 10. I'll use this formula.

<script>
  let min = 5,
    max = 10;
  
  let rnd = Math.random() * (max - min) + min;
  document.write(Math.floor(rnd));     // Rounding off the value using Math.floor() function.
</script>
Try it

I have defined the maximum and minimum numbers in variables and using Math.random() I am generating a random number between this range. I have used Math.floor() function to round off the value.

We can make it more dynamic by allowing users to input the min. and max. values. To do this, I am adding two textboxes.

<body>
  <p>Minimum: <input type='textbox' id='min'></p>
  <p>Maximum: <input type='textbox' id='max'></p>
  
  <p>
    <input type='button' value='Generate Random Number' onclick="generateRnd()">
  </p>
  
  <p id='result'></p>
</body>

<script>
  let generateRnd = () => {
    let min = Math.ceil(document.getElementById('min').value), 
    max = Math.floor(document.getElementById('max').value);
  
    let rnd = Math.random() * (max - min) + min;
    document.getElementById('result').innerHTML = Math.floor(rnd);
  }
</script>
Try it

← PreviousNext →