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:
xxxxxxxxxx
1
const min = 10; // inclusive
2
const max = 15; // exclusive
3
4
const value = min + (max - min) * Math.random();
5
6
console.log(value);
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:
xxxxxxxxxx
1
/**
2
* Generates random value in range.
3
*
4
* @param min inclusive minimal value (used as max value when max argument is undefined)
5
* @param max exclusive maximal value
6
*
7
* @returns random float number in range <min, max)
8
*/
9
const randomFloat = (min, max) => {
10
if (max == null) {
11
max = (min == null ? Number.MAX_VALUE : min);
12
min = 0.0;
13
}
14
if (min >= max) {
15
throw new Error("Incorrect arguments.");
16
}
17
return min + (max - min) * Math.random();
18
};
19
20
21
// Usage example:
22
23
console.log(randomFloat()); // 1.67319916301163e+308
24
console.log(randomFloat(5)); // 2.7593705936801918
25
console.log(randomFloat(10, 80)); // 37.54521514384005
26
console.log(randomFloat(-50, 50)); // -30.632843429520975