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

6

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

    
asked by Eduardo Sebastian 16.01.2018 в 04:08
source

2 answers

5

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" />
    
answered by 16.01.2018 / 05:38
source
4

The main thing would be to remove the floor thus avoiding truncating the decimal and avoiding returning an integer to remove the +1 to avoid taking values greater than the last number passed,

var max = 3,
min = 1 ,
//Retorna un número aleatorio entre min (incluido) y max (excluido)
random = Math.random() * (max - min) + min;
console.log(random);

If you want to limit the number of decimals you can always use toFixed , (2 for the example)

var max = 3,
min = 1 ,
random = (Math.random() * (max - min) + min).toFixed(2);
console.log(random);
    
answered by 16.01.2018 в 05:15