How to get random number with decimals and integers in JavaScript?

Question:

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 within 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?

Answer:

Think of it this way: a random between 4 and 10 with 1 decimal would be the same as one between 40 and 100, divided by 10, right? … Well, generalizing:

//Aleatorio entre min y max (incluyendo a max) con n decimales
//
function aleatorio(minimo, maximo, decimales) {
    var precision = Math.pow(10, decimales);
    minimo = minimo*precision;
    maximo = maximo*precision;
    return Math.floor(Math.random()*(maximo-minimo+1) + minimo) / precision;
}


Demo:

function aleatorio(minimo, maximo, decimales) {
    var precision = Math.pow(10, decimales);
    minimo = minimo*precision;
    maximo = maximo*precision;
    
    return Math.floor(Math.random()*(maximo-minimo+1) + minimo) / precision;
}


//Calcular
document.getElementById("calc")
    .addEventListener(
        "click",
        function (event) {
            var min = document.getElementById("min").value,
                max = document.getElementById("max").value,
                decimales = document.getElementById("decimales").value,
                resultado = document.getElementById("resultado");
            
            resultado.innerText = aleatorio(min,max,decimales);
        }
    );
input {
    width: 100%;
}
Min:
<input id="min" type="number" value="1">
Max:
<input id="max" type="number" value="3">
Decimales:
<input id="decimales" type="number" value="1">
<input id="calc" type="button" value="Calcular">
Aleatorio:
<pre id="resultado" />
Scroll to Top