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:

.highlight{
  color:green;
}

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:

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 : <span class="highlight">'+getRandomNumberBetween(parseInt(start),parseInt(end))+'</span>';
}

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

You can follow the video for detail instructions and demo:



Recommended For You

About the Author: Admin