Forum Moderators: open
I need a javascript code that can give me a random integer from two specified numbers. These will change so I need like a function or something that will do it for me.
Ex:
from 2-9 or
from 300-329
sorta like PHP's rand(2,9) thing.
Any help is appreciated!
[edited by: PokeTech at 9:34 pm (utc) on May 10, 2009]
The only complication here is that with your example, you'd want to scale to 7, then add an offset of 2 (first example), or scale to 29, then add an offset of 300 (second example).
So, get a random number (typically between 0 and 1), then multiply by the scale (max-min), then add the offset (min) to get the scaled and offset result.
You may also want to force an integer result on the multiplication or final result, depending on what you wish to use the random number for.
Jim
here is the basic script...
[blue]
<script type="text/javascript">
[/blue][blue]
min=2;
max=9;
[/blue][blue]
num=Math.floor(Math.random()*max-min+1)+min;
[/blue][blue]
alert(num)
[/blue][blue]
</script>[/blue]
sorry about that I forgot brackets.
It should be...
[blue]
<script type="text/javascript">
[/blue][blue]
min=2;
max=9;
[/blue][blue]
num=Math.floor(Math.random()*(max-min+1))+min;
[/blue][blue]
alert(num)
[/blue][blue]
</script>
[/blue]