Getting a Random Number Within a Range
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.
why need (Math.random() % 1) ?
Hm, good point. Removed!
Hmm, calling rand(50, 100) would give you a number between 50 and 101, I suppose “+ 1″ should be removed?
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?
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?
Hi again Patrik,
I just looked into this and found that Math.random() should never return 1.
Ok, I’m really sorry for not knowing that. Then everything looks fine :) Thanks for your time!