0

I know about random that generates a random number between 0 and 1.

Math.random();

But how can I generate a random number between 1 and 2,147,483,647 using Javascript?

Alan2
  • 23,493
  • 79
  • 256
  • 450
  • True random numbers aren't really possible, as generating a number is inherently deterministic. Nonetheless, a pseudo random number generator is usually *good enough* for almost all purposes. – Rushy Panchal Jun 23 '16 at 02:59
  • 1
    https://en.wikipedia.org/wiki/Pseudorandom_number_generator – SLaks Jun 23 '16 at 02:59
  • 3
    flip a coin 32 times, then use javascript to convert the binary representation of your results to decimal :) – juanpa.arrivillaga Jun 23 '16 at 03:03
  • 3
    [`Math.random = () => 4 /* chosen by a fair dice roll. guaranteed to be random. */`](https://xkcd.com/221/) – Patrick Roberts Jun 23 '16 at 03:05
  • 1
    I had to upvote @PatrickRoberts comment, but in case you were actually thinking about it, don't use it :p – zeterain Jun 23 '16 at 03:20

2 Answers2

2

You can simply multiply Math.random() times the limit value and then round down. Since Math.random() returns a decimal value between 0 and 1, you will always get some scaled proportion of your limit value so your result will be between 0 and your limit value.

If you want the result to be an integer, then use can call Math.floor() on the result of the multiplication to round down to an integer.

Since you also want the lowest value to be 1 instead of 0 and you want the result to include the limit value, then you can add 1 to the result to put it in the exact range.

var maxInt = 2147483647;   // max 32-bit signed int

function randomInt() {
    // generate random value between 1 and maxInt inclusive of both values
    return Math.floor(Math.random() * maxInt) + 1;
}

Working demo: https://jsfiddle.net/jfriend00/ntkokacf/

jfriend00
  • 683,504
  • 96
  • 985
  • 979
1

In order to find a number you can do something to the effect of:

var randomNumber = Math.floor(Math.random() * 2147483647);

You can also write a function to repeat that and that will allow for any minimum or maximum:

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

The explanation of the function is that it asks for a minimum and a maximum number. Whatever the minimum number is, we add to the second half of the return statement. The second half needs to give us the number of different possible numbers between min and max, so we multiply Math.random() by that exact number, which is the difference between max and min plus one. The problem is that this gives a decimal, therefore we take the floor of that to get rid of the decimal.

Zachary Weixelbaum
  • 904
  • 1
  • 11
  • 24