javascript-random-number-range
Javascript

Random Number between Range in JavaScript

Math.random() is a function that returns a pseudo-random floating numbers between 0 and 1 (0 is inclusive, 1 is exclusive) We usually multiply the result with other numbers to scale the randomized value. However, there are some considerations that require more than simple multiplication if you need a precise result range or negative values is involved.

For weighted random or normal distributed random with JavaScript, read this article instead.

Snippet 1 (Integer Range)

Return integer between min and max (inclusive) Negative numbers are supported.

let random = Math.floor(Math.random()*(max-min+1)+min);
Note
Math.round() can’t be used as it causes not-uniform distribution (unequal chance of random). Math.round() returns 0 for values between [0,0.5) and returns 1 for values between [0.5,1]  This halve the probability of getting 0 while Math.floor always returns 0 for every numbers.

Snippet 2 (Floating Number Range)

Return float between min and max (min is inclusive, max is Exclusive)

let random = Math.random() * (max - min) + min;

Snippet 3 (Generalized)

This method uses chance.js library. You’ll need to include the following line in your HTML or import it into your project.

<script src="https://cdnjs.cloudflare.com/ajax/libs/chance/1.0.18/chance.min.js"></script>

This line returns floating number between -100 to 100 (inclusive)

let random = chance.floating({ min: -100, max: 100 });

This line returns floating number between -5000 to 500 with 7 digits after decimal point (inclusive)

chance.floating({ min: -5000, max: 500, fixed: 7 });
Note
The “fixed” argument does NOT guarantee the trailing zeroes. For example, if the random result is 45612.9003.. and the fixed argument is 3, the actual value returned from the function is 45612.9

Leave a Reply

Your email address will not be published. Required fields are marked *