Generate random integer between two numbers using JavaScript

Random number generation is the generation of a sequence of numbers or symbols that cannot be reasonably predicted better than by a random chance, usually through a random-number generator (RNG). Computer random number generators are important in mathematics, cryptography and gambling (on game servers).

In this article, we will be generating a random integer between given two numbers using JavaScript. We will be generating a random number in a given range using JavaScript Math Object.

We often need to generate a random number within a specified range in realtime applications. The logic dealt below can be very useful in situations like this.

Fundamental Concept

Math.floor(Math.random() * ((y-x)+1) + x);

Math.random() returns a random number between 0 (inclusive) and 1 (exclusive).

Math.floor() rounds a number downward to its nearest integer.

Generating JavaScript random number

CSS:

<style>
.highlight{
  color:green;
}
</style>

HTML:

 

<h1>Generate Random Number Using JavaScript</h1>

Random Number Between and
<input type=”button” value=”Get Number” onclick=”getRandomNumber();”>

<h2 class=”number”></h2>

 

JavaScript:

  
  // Generating JavaScript random number

  
  function getRandomNumberBetween(start,end){
    return Math.floor(Math.random()*(end-start+1))+start;
  }

  function getRandomNumber(){
    var start = document.getElementsByClassName('start')[0].value;
    var end = document.getElementsByClassName('end')[0].value;
    document.getElementsByClassName('number')[0].innerHTML = 'The Random Number is : '+getRandomNumberBetween(parseInt(start),parseInt(end))+'';
  }

In this way, we can generate random integer between two numbers using JavaScript.

You can follow the video for detail instructions and demo:

Leave a Reply