[Solved-5 Solutions] Generate random number between two numbers in JavaScript - javascript tutorial



Problem:

How to generate a random number in JavaScript ?

Solution 1:

If we need to get the numbers between 1 and 10, we would calculate:

Math.floor(Math.random() * 10) + 1  

Where,

  • 1 is the starting number
  • 10 is the number of possible results (1 + start (10) - end (1))

Solution 2:

Random intervals to be allowed that do not start with 1.

function randomIntFromInterval(min,max)
{
    return Math.floor(Math.random()*(max-min+1)+min);
}

Solution 3:

This is one of the solution:

(Math.random() * 6 | 0) + 1
~~(Math.random() * 6) + 1

Solution 4:

You can try this:

var x = 12; // can be any number
var rand = Math.floor(Math.random()*x) + 1;

Solution 5:

To generate a lot of random numbers between both positive and negative.

function randomBetween(min, max) {
    if (min < 0) {
        return min + Math.random() * (Math.abs(min)+max);
    }else {
        return min + Math.random() * max;
    }
}


Related Searches to Generate random number between two numbers in JavaScript - javascript tutorial