Alan - 10 months ago 33

Javascript Question

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?

Answer

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;
}
```