Home > Article > Web Front-end > Detailed explanation of how to use Math.floor and Math.random to get random integers_Basic knowledge
Math.random(): Get 0~1 random number
Math.floor() method rounds a number DOWNWARDS to the nearest integer, and returns the result. (less than or equal to x, and the integer closest to x.)
In fact, the return value is the integer digit of the number:
Math.floor(0.666) --> 0
Math.floor(39.2783) --> 39
So we can use Math.floor(Math.random()) to get the integer in a range you want.
For example: Now we want to pick a random number from 1 to 52:
First Math.random()*52 //In this way we can get a number with >=0 and <52
Then Add 1: Math.random()*52 1 //Now this number is >=1 and <53
and then use Math.floor to round
Finally: Math.floor(Math.random()*52 1)
This will give you a random integer with a value ranging from 1 to 52.