Generate a Random Number between 2 values to 2 decimals places in Javascript
You were very close, what you need is not to work with decimal numbers as min and max. Let's have max = 1000 and min = 100, so after your Math.floor you will need to divide by 100:
var randomnum = Math.floor(Math.random() * (1000 - 100) + 100) / 100;
Or if you want to work with decimals:
var precision = 100; // 2 decimals
var randomnum = Math.floor(Math.random() * (10 * precision - 1 * precision) + 1 * precision) / (1*precision);
Multiply the original random number by 10^decimalPlaces
, floor it, and then divde by 10^decimalPlaces
. For instance:
floor(8.885729840652472 * 100) / 100 // 8.88
function genRand(min, max, decimalPlaces) {
var rand = Math.random()*(max-min) + min;
var power = Math.pow(10, decimalPlaces);
return Math.floor(rand*power) / power;
}
for (var i=0; i<20; i++) {
document.write(genRand(0, 10, 2) + "<br>");
}
Edit in response to comments:
For an inclusive floating-point random function (using this answer):
function genRand(min, max, decimalPlaces) {
var rand = Math.random() < 0.5 ? ((1-Math.random()) * (max-min) + min) : (Math.random() * (max-min) + min); // could be min or max or anything in between
var power = Math.pow(10, decimalPlaces);
return Math.floor(rand*power) / power;
}