JavaScript - How to generate Random number in a given Range

← PrevNext →

The Math.random() method in JavaScript generates a random number between 0 and 1. To generate a random number within a specific range, you need a different formula. Learn how to use Math.random() to create random numbers between any two values in JavaScript.

Try this.

Enter number range and click the "Generate Random Number" button.

Math.random() function

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 minimum and maximum numbers as variables. Using Math.random(), I generate a random number within this range. To round off the value, I use the Math.floor() function.

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 →