+ 5
Rand()
Is there an equivalent of rand () in javascript?
4 Respostas
+ 5
Hello, Omar Alex !
The function Math.random returns a random fractional number from 0 to 1.
Syntax
Math.random();
To get a random number in a certain interval (fractional or whole), you should use special methods:
Random fractional number between min and max
function getRandomArbitary (min, max) {
return Math.random() * (max - min) + min;
}
https://www.sololearn.com/Course/JavaScript/?ref=app
+ 4
Math.random() is used.However it returns float values between 0 and 1.
To get integer values use:
Math.ceil(Math.random()) or Math.floor(Math.random()).
Eg:
To generate a no between 0 and 100
You can use.
Math.ceil(Math.random()*99) or Math.floor(Math.random()*100).
Hope this helps you,Omar Alex .
+ 4
Use this function:
function boundValue(min,max)
{
return Math.random()*(max-min)+min;
}
The value returned is bound by min & max values.
min <= x <= max
e.g.
min = 2 , max = 4;
for(var i=0; i<20; i++)
{
console.log(boundValue(min,max));
}
will return 20 values between 2 & 4
0
If you want an integer, use Math.floor(/*numbers here*/) to remove the decimals.