I can get random numbers in a custom range, with:
Math.floor(Math.random() * ( maximo - minimo + 1 ) + minimo )
Example:
var max = 10,
min = 4,
random = Math.floor(Math.random() * (max - min + 1) + min);
console.log(random);
But how can I get numbers between a certain range, including decimals between them?
For example, I want to get the numbers 1 - 3 , and the first decimal included, the options would be:
[1, 1.1, 1.2, 1.3 .... 3] ,
How can I do it in JavaScript?
Think of it this way: a random between 4 and 10 to 1 decimal would be the same as one between 40 and 100, divided by 10, right? ... Well, generalizing:
demonstration:
The main thing would be to remove the
floor
so you avoid truncating the decimal and avoid returning only an integer remove the+1
to avoid taking values greater than the maximum number passed,If you want to limit the number of decimal places you can always fall back to
toFixed
, (2 for the example)