javascript tutorial - [Solved-5 Solutions] Generating random whole numbers in JavaScript in a specific range - javascript - java script - javascript array



Problem:

How to generate a random whole number between two specified variables in JavaScript

Solution 1:

/**
 * Returns a random number between min (inclusive) and max (exclusive)
 */
function getRandomArbitrary(min, max) {
    return Math.random() * (max - min) + min;
}

/**
 * Returns a random integer between min (inclusive) and max (inclusive)
 * Using Math.round() will give you a non-uniform distribution!
 */
function getRandomInt(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}
click below button to copy the code. By JavaScript tutorial team

Solution 2:

var randomnumber = Math.floor(Math.random() * (maximum - minimum + 1)) + minimum;
click below button to copy the code. By JavaScript tutorial team

Solution 3:

function getRandomizer(bottom, top) {
    return function() {
        return Math.floor( Math.random() * ( 1 + top - bottom ) ) + bottom;
    }
}
click below button to copy the code. By JavaScript tutorial team

usage:

var rollDie = getRandomizer( 1, 6 );

var results = ""
for ( var i = 0; i<1000; i++ ) {
    results += rollDie() + " ";    //make a string filled with 1000 random numbers in the range 1-6.
}
click below button to copy the code. By JavaScript tutorial team

Solution 4:

// Returns a random integer between min and max

function getRandomInt(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}
click below button to copy the code. By JavaScript tutorial team

Useful Examples:

// 0 - 10
Math.floor(Math.random() * 11);

// 1 - 10
Math.floor(Math.random() * 10) + 1;

// 5 - 20
Math.floor(Math.random() * 16) + 5;

// -10 - (-2)
Math.floor(Math.random() * 9) - 10;
click below button to copy the code. By JavaScript tutorial team

Solution 5:

function randomRange(min, max) {
  return ~~(Math.random() * (max - min + 1)) + min
}
click below button to copy the code. By JavaScript tutorial team

Related Searches to javascript tutorial - Generating random whole numbers in JavaScript in a specific range