skip to Main Content

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();

2

Answers


  1. Chosen as BEST ANSWER

    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

  2. The subtle crypto interface provides a method. Node.js includes this library as well. From MDN

    Crypto: getRandomValues() method

    The Crypto.getRandomValues() method lets you get cryptographically
    strong random values. The array given as the parameter is filled with
    random numbers (random in its cryptographic meaning).

    To guarantee enough performance, implementations are not using a truly
    random number generator, but they are using a pseudo-random number
    generator seeded with a value with enough entropy. The pseudo-random
    number generator algorithm (PRNG) may vary across user agents, but is
    suitable for cryptographic purposes.

    console.log(self.crypto.getRandomValues(new Uint32Array(1))[0]);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search