EN
JavaScript - random float number in range with exclusive max value example
11
points
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:
randomFloat()
Returns a random number in the range0
toNumber.MAX_VALUE
(1.7976931348623157e+308
)randomFloat(max)
Returns a random number in the range from0
tomax
.randomFloat(min, max)
Returns a random number in the range frommin
tomax
.
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