Languages
[Edit]
EN

JavaScript - get random double between 2 numbers

10 points
Created by:
Root-ssh
177980

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 range minmax (inclusive min, exclusive max) with approximately uniform distribution over that range.

 

References

  1. Math.random method - MDN docs

Alternative titles

  1. JavaScript - get random double in range
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