I want to generate a random number between 1 and 10 up to 2 decimal places,
I'm currently using this below to generate my numbers,
var randomnum = Math.floor(Math.random() * (10.00 - 1.00 + 1.00)) + 1.00;
Ultimately, I would like to know how to generate numbers like:
1.66
5.86
8.34
In the format: var randomnum = then the code
sidenote: I don't remember why I previously had generated my numbers like that but remember something about Math.random generating numbers to 8 decimal places.
Thank you for the help! :)
Ps: I've seen a lot of posts about waiting to round down or up generated numbers and haven't found one wanting to generate them straight out.
UPDATE: I want a number value not a string that looks like a number
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;
}
You can use below code.
var randomnum = (Math.random() * (10.00 - 1.00 + 1.00) + 1.00).toFixed(2);
Just to simplify things visually, mathematically and functionally based on the examples above.
function randomNumberGenerator(min = 0, max = 1, fractionDigits = 0, inclusive = true) {
const precision = Math.pow(10, Math.max(fractionDigits, 0));
const scaledMax = max * precision;
const scaledMin = min * precision;
const offset = inclusive ? 1 : 0;
const num = Math.floor(Math.random() * (scaledMax - scaledMin + offset)) + scaledMin;
return num / precision;
};
The Math.max
protects against negative decimal places from fractionDigits
A more way with typescript/angular example:
getRandom(min: number, max: number) {
return Math.random() * (max - min) + min;
}
console.log('inserting min and max values: ', this.getRandom(-10.0, -10.9).toPrecision(4));
getting random values between -10.0 and -10.9