JavaScript - how to get random double between 2 numbers?

10 points
Created by:

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 minÔÇômax┬á(inclusive┬ámin, exclusive┬ámax) with approximately uniform distribution over that range.


  1. Math.random method - MDN docs
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.

ÔŁĄ´ŞĆ­čĺ╗ ­čÖé