Search code examples
javascriptrandom

How to generate a random whole positive number in Javascript with no specific range


I need a method that generates a positive whole number, any number. Couldn't found any answer that specify those exact requirements - any positive && whole number.

Basically I'm looking for something like that:

const randomNumber = getWholePositiveNum();

Solution

  • Here is a solution I found:

    console.log(Math.floor(Math.random() * Number.MAX_SAFE_INTEGER) + 1)

    • Math.random() provides an evenly distributed decimal between 0 and 1
    • Multiplying by Number.MAX_SAFE_INTEGER scales it to the desired range - max safe integer value in JS, which is 9007199254740991
    • Math.floor() converts it to an integer (whole)
    • Adding 1 makes the range start at 1 instead of 0