How can you pick randomly a float between 0 and 1 in javascript?

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 

Bài mới nhất

Chủ Đề