Random Numbers

JavaScript FAQ | JavaScript Numbers FAQ  

Question: How do I generate random numbers in JavaScript?

Answer: To generate random floating-point numbers in the range from 0 to 1, use the

Math.random()
method:
num = Math.random()  // num is random, from 0 to 1 
If you need random floating-point numbers in the range from
A
to
B
(
A<B
), use this code:
num = A + (B-A)*Math.random()  // num is random, from A to B 
For a random integer in the range from
M
to
N
(where
M
and
N
are two integers,
M
<
N
) use:
num = Math.floor(M + (1+N-M)*Math.random())  // num is random integer from M to N 

Copyright © 1996-2018, JavascriptFAQ.net.