Forum Moderators: open

Message Too Old, No Replies

Generate random number between.

2-9, 300-329, etc.

         

PokeTech

9:33 pm on May 10, 2009 (gmt 0)

10+ Year Member



I can't seem to find this code anywhere so I'll just ask to see if anyone knows it.

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]

jdMorgan

10:33 pm on May 10, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



A search for javascript random number turns up many results, and the first result is scalable, just as you require.

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

birdbrain

10:40 pm on May 10, 2009 (gmt 0)



Hi there PokeTech,

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]


birdbrain

PokeTech

11:31 pm on May 10, 2009 (gmt 0)

10+ Year Member



I've had a few times where that returns a 1.

birdbrain

11:56 pm on May 10, 2009 (gmt 0)



Hi there PokeTech,

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]

birdbrain