EN
JavaScript - get random double between 2 numbers
10
points
In this article, we would like to show you how to generate a random number from the range in JavaScript.
Practical example
// ONLINE-RUNNER:browser;
var generateNumber = function(min, max) {
if (min > max) {
throw new Error('Minimum value should be smaller than maximum value.');
}
var range = max - min;
return min + range * Math.random();
};
// Usage example: // Example output
console.log(generateNumber(-5, +5)); // -1.3454228839144022
console.log(generateNumber(+2, +7)); // 4.329747095168658
console.log(generateNumber(0, 1000)); // 44.21996785621873
Note:
generateNumber
method returns a floating-point, pseudo-random number in the rangemin
–max
(inclusivemin
, exclusivemax
) with approximately uniform distribution over that range.