Generate random number between two numbers in JavaScript

Mirgorod Source

Is there a way to generate a random number in a specified range (e.g. from 1 to 6: 1, 2, 3, 4, 5, or 6) in JavaScript?

javascriptrandom

Answers

answered 8 years ago khr055 #1

If you wanted to get between 1 and 6, you would calculate:

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

Where:

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

answered 8 years ago ryebr3ad #2

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

answered 7 years ago Francisc #3

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

What it does "extra" is it allows random intervals that do not start with 1. So you can get a random number from 10 to 15 for example. Flexibility.

answered 7 years ago Vishal #4

Other solutions:

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

answered 6 years ago Petter Thowsen #5

Math is not my strong point, but I've been working on a project where I needed 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;
    }
}

E.g

randomBetween(-10,15)//or..
randomBetween(10,20)//or...
randomBetween(-200,-100)

Of course, you can also add some validation to make sure you don't do this with anything other than numbers. Also make sure that min is always less than or equal to max.

answered 5 years ago Rastus Oxide #6

I found Francisc's solution above did not include the min or max number in the results, so I altered it like this:

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

answered 4 years ago Lior Elrom #7

Math.random()

From the Mozilla Developer Network documentation:

// Returns a random integer between min (include) and max (include)

Math.floor(Math.random() * (max - min + 1)) + min;

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;

answered 4 years ago Erdi İzgi #8

I was searching random number generator written in TypeScript and I have written this after reading all of the answers, hope It would work for TypeScript coders.

    Rand(min: number, max: number): number {
        return (Math.random() * (max - min + 1) | 0) + min;
    }   

answered 4 years ago vladiim #9

Or, in Underscore

_.random(min, max)

answered 4 years ago Travis #10

Sense you need to add 1 to the max number, and then subtract the minimum number for any of this to work, and I need to make a lot of random Integers, this function works.

var random = function(max, min) {
    high++;
    return Math.floor((Math.random()) * (max - min)) + min;
};

This works with both negative, and positive numbers, and I'm working on decimals for a library.

answered 3 years ago ElChupacabra #11

I wrote more flexible function which can give you random number but not only integer.

function rand(min,max,interval)
{
    if (typeof(interval)==='undefined') interval = 1;
    var r = Math.floor(Math.random()*(max-min+interval)/interval);
    return r*interval+min;
}

var a = rand(0,10); //can be 0, 1, 2 (...) 9, 10
var b = rand(4,6,0.1); //can be 4.0, 4.1, 4.2 (...) 5.9, 6.0

Fixed version.

answered 2 years ago Jeremy Banks #12

Instead of Math.random(), you can use crypto.getRandomValues() to generate evenly-distributed cryptographically-secure random numbers. Here's an example:

function randInt(min, max) {
  var MAX_UINT32 = 0xFFFFFFFF;
  var range = max - min;

  if (!(range <= MAX_UINT32)) {
    throw new Error(
      "Range of " + range + " covering " + min + " to " + max + " is > " +
      MAX_UINT32 + ".");
  } else if (min === max) {
    return min;
  } else if (!(max > min)) {
    throw new Error("max (" + max + ") must be >= min (" + min + ").");
  }

  // We need to cut off values greater than this to avoid bias in distribution
  // over the range.
  var maxUnbiased = MAX_UINT32 - ((MAX_UINT32 + 1) % (range + 1));

  var rand;
  do {
    rand = crypto.getRandomValues(new Uint32Array(1))[0];
  } while (rand > maxUnbiased);

  var offset = rand % (range + 1);
  return min + offset;
}

console.log(randInt(-8, 8));          // -2
console.log(randInt(0, 0));           // 0
console.log(randInt(0, 0xFFFFFFFF));  // 944450079
console.log(randInt(-1, 0xFFFFFFFF));
// Uncaught Error: Range of 4294967296 covering -1 to 4294967295 is > 4294967295.
console.log(new Array(24).fill().map(n => randInt(8, 12)));
// [11, 8, 8, 11, 10, 8, 8, 12, 12, 12, 9, 9,
//  11, 8, 11, 8, 8, 8, 11, 9, 10, 12, 9, 11]
console.log(randInt(10, 8));
// Uncaught Error: max (8) must be >= min (10).

answered 2 years ago Sebastián Lara #13

Example

Return a random number between 1 and 10:

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

The result could be: 3

Try yourself: here

--

or using lodash / undescore:

_.random(min, max)

Docs: - lodash - undescore

answered 2 years ago Arun Sharma #14

Inspite of many answers and almost same result. I would like to add my answer and explain its working. Because it is important to understand its working rather than copy pasting one line code. Generating random numbers is nothing but simple maths.

CODE:

function getR(lower, upper) {

  var percent = (Math.random() * 100);
  // this will return number between 0-99 because Math.random returns decimal number from 0-0.9929292 something like that
  //now you have a percentage, use it find out the number between your INTERVAL :upper-lower 
  var num = ((percent * (upper - lower) / 100));
  //num will now have a number that falls in your INTERVAL simple maths
  num += lower;
  //add lower to make it fall in your INTERVAL
  //but num is still in decimal
  //use Math.floor>downward to its nearest integer you won't get upper value ever
  //use Math.ceil>upward to its nearest integer upper value is possible
  //Math.round>to its nearest integer 2.4>2 2.5>3   both lower and upper value possible
  console.log(Math.floor(num), Math.ceil(num), Math.round(num));
}

answered 2 years ago Razan Paul #15

jsfiddle: https://jsfiddle.net/cyGwf/477/

Random Integer: to get a random integer between min and max, use the following code

function getRandomInteger(min, max) {
  min = Math.ceil(min);
  max = Math.floor(max);
  return Math.floor(Math.random() * (max - min)) + min;
}

Random Floating Point Number: to get a random floating point number between min and max, use the following code

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

Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random

answered 1 year ago Faiz Mohamed Haneef #16

The Math.random() function returns a floating-point, pseudo-random number in the range [0, 1); that is, from 0 (inclusive) up to but not including 1 (exclusive)

Let's add the min randomly from 0 to max-min

Case 0

min + 0 * (max-min) = min

Case 1

min + 1 * (max-min) = max

Random Case using Math.random 0 <= r < 1

min + r * (max-min) = X, where X has range of min <= X < max

The above result X is a random numeric. However due to Math.random() our left bound is inclusive, and the right bound is exclusive. To include our right bound we increase the right bound by 1 and floor the result.

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

To get the random number

generateRandomInteger(-20, 20);

answered 1 year ago Sarvesh Kesharwani #17

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

comments powered by Disqus