scriptNode

Web development with a focus on JavaScript RSS

Getting a Random Number Within a Range

Novice Matt Hackett Published June 21st, 2008 by Matt Hackett

Getting a random number in JavaScript is easy. Just use Math.random(). The problem is that this returns a huge float between 0 and 1. It's pretty trivial to get something useful out of it, such as a random number between 0 and X, but typically the behavior a developer wants is within a range, for example from 50 to 100 (like the terrific rand() function provides in PHP).

Here's a simple script to get a random range:

Try the button below to get a random number between 50 and 100:

It's that easy! Enjoy.

Read other articles tagged: , ,

Comments (7)

  • Unknown user
    July 8th, 2008 qing said…

    why need (Math.random() % 1) ?

  • Matt Hackett

    Hm, good point. Removed!

  • Unknown user
    July 9th, 2008 Patrik said…

    Hmm, calling rand(50, 100) would give you a number between 50 and 101, I suppose “+ 1″ should be removed?

  • Matt Hackett

    I don’t think so, Patrik. I’ve done extensive tests on this and haven’t found a return value outside of the given integer range. Have you found a bad return?

  • Unknown user
    July 22nd, 2008 Patrik said…

    If I’m not wrong, Math.random() can return 1 as a value. You would then get the equation 50 + (100 - 50 + 1) * 1 which will be 101. Or am I missing something here?

  • Matt Hackett

    Hi again Patrik,

    I just looked into this and found that Math.random() should never return 1.

  • Unknown user
    July 23rd, 2008 Patrik said…

    Ok, I’m really sorry for not knowing that. Then everything looks fine :) Thanks for your time!

Thoughts?

(required)

© 2009 scriptNode