Languages
[Edit]
EN

JavaScript - random float number in range with exclusive max value example

11 points
Created by:
Kadeem-Craig
516

In JavaScript, it is possible to randomize a float number in a range with an exclusive max value in the following ways.

Quick solution:

// ONLINE-RUNNER:browser;

const min = 10;  // inclusive
const max = 15;  // exclusive

const value = min + (max - min) * Math.random();

console.log(value);

 

Reusable code example

In this section, you can find a reusable function that lets to generate random float numbers in the range.

The below function can be used in three cases:

  1. randomFloat()
    Returns a random number in the range 0 to Number.MAX_VALUE (1.7976931348623157e+308)
  2. randomFloat(max)
    Returns a random number in the range from 0 to max.
  3. randomFloat(min, max)
    Returns a random number in the range from min to max.

Source code:

// ONLINE-RUNNER:browser;

/**
 * Generates random value in range.
 * 
 * @param min inclusive minimal value (used as max value when max argument is undefined)
 * @param max exclusive maximal value
 * 
 * @returns random float number in range <min, max)
 */
const randomFloat = (min, max) => {
    if (max == null) {
        max = (min == null ? Number.MAX_VALUE : min);
        min = 0.0;
    }
    if (min >= max) {
        throw new Error("Incorrect arguments.");
    }
    return min + (max - min) * Math.random();
};


// Usage example:

console.log(randomFloat());        // 1.67319916301163e+308
console.log(randomFloat(5));       // 2.7593705936801918
console.log(randomFloat(10, 80));  // 37.54521514384005
console.log(randomFloat(-50, 50)); // -30.632843429520975

See also

  1. JavaScript - Math.random() method example
  2. JavaScript - random float number in range with inclusive max value example

Alternative titles

  1. JavaScript - randomize float number in range with exclusive max value example
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

JavaScript - random

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join