We have a form with 2 fields and a button. We want on button click to output random int number (like 3, 5 or 33) which would lie between int A and int B? (no use of jQuery or anything like it is required)
Asked
Active
Viewed 6,297 times
3 Answers
12
You can use Javascript Math.random
function randomInRange(start,end){
return Math.floor(Math.random() * (end - start + 1) + start);
}

Samet Atdag
- 982
- 6
- 21
-
give it 33 and 44 and get 4=) – Rella Dec 30 '10 at 02:24
-
I called this function in a 1000 times for loop, all gives results in between 33 and 44. – Samet Atdag Dec 30 '10 at 08:03
-
@rella you can't get 4 as result sum of positive number and 33. you will get at least 33 :) – Sergey Sob Nov 26 '17 at 10:19
3
Use something like Math.floor(Math.random()*(intB-intA +1)) + intA
?

ThiefMaster
- 310,957
- 84
- 592
- 636

Sebastiaan van den Broek
- 5,818
- 7
- 40
- 73
2
Like this:
Math.floor(a + Math.random() * (b - a))
The Math.random()
method returns a random floating-point number in the range [0,1) — that is, between 0 (inclusive) and 1 (exclusive).

Zsolt Meszaros
- 21,961
- 19
- 54
- 57

SLaks
- 868,454
- 176
- 1,908
- 1,964
-
I think (re-reading both the question and the code carefully) the OP might want to multiply `(b + 1 - a)` not `(a - b)`. – Michael Lorton Dec 30 '10 at 00:33