Languages
[Edit]
EN

JavaScript - how to get random double between 2 numbers?

10 points
Created by:
Root-ssh
119890

In JavaScript it is possible to generate random number from range in following way.

1. Custom random logic 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

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