Home

Javascript: How to generate random numbers within a range

This post covers ways you can generate floats, integers and big integers (BigInts) within a certain range (min, max) using pure javascript (no dependencies).

Floats

Generate random float between 0 and 1

/** Generates floats between 0 (inclusive) and 1 (exclusive) */
function generateRandomFloat() {
  return Math.random();
}

Generate random float between low and high

/** Generates floats between low (inclusive) and high (exclusive) */
function generateRandomFloat(low, high) {
  return low + Math.random() * (high - low);
}

Integers

Generate random integer between low and high

/** Generates integers between low (inclusive) and high (exclusive) */
function generateRandomInteger(low, high) {
  const lowCeil = Math.ceil(low);
  const highFloor = Math.floor(high);
  const randomFloat = lowCeil + Math.random() * (highFloor - lowCeil);

  return Math.floor(randomFloat);
}

Large numbers (BigInts)

Generate random BigInt between low and high

Bellow is a creative implementation. If you need more performance, consider using libraries.

/** Generates BigInts between low (inclusive) and high (exclusive) */
function generateRandomBigInt(lowBigInt, highBigInt) {
  if (lowBigInt >= highBigInt) {
    throw new Error('lowBigInt must be smaller than highBigInt');
  }

  const difference = highBigInt - lowBigInt;
  const differenceLength = difference.toString().length;
  let multiplier = '';
  while (multiplier.length < differenceLength) {
    multiplier += Math.random()
      .toString()
      .split('.')[1];
  }
  multiplier = multiplier.slice(0, differenceLength);
  const divisor = '1' + '0'.repeat(differenceLength);

  const randomDifference = (difference * BigInt(multiplier)) / BigInt(divisor);

  return lowBigInt + randomDifference;
}

More Resources