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);
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 });