LanguagesJavaScriptRandom Number Generator

Random Number Generator

Developer.com content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.


Mr. Tip, I presume?

Okay, hey! New script this week! This script is great in that it produces a random number between 1 and any number. You can set the upper limit within the script. The output of the script looks like this:

And here’s what it all looks like:

 

<script language="JavaScript">
<!--
function RandomNumber(upper_limit) 
{ 
return Math.round(upper_limit * Math.random()); 
}
//-->
</script>

<script language="JavaScript">
<!--
var upper_limit = 50;
document.write('Here is a random number between 0 and ' 
+ upper_limit + ':<P><center>');
document.write(RandomNumber(upper_limit) + '</center>');
//-->
</script> 
 


Wait (you yell)! That’s not one script, that’s two!

Yup.

But they work with each other. The first script actually creates the random number. The second is mainly there to set the upper limit and display the results. It’s a pretty clever script. Look at the line that creates the random number to start it off.

 

return Math.round(upper_limit * Math.random());


Let’s break it down so it’s readable. “Math” is an object, but it’s a strange object. It itself isn’t really anything except a socket with which you can connect methods. It’s just that when you use the Math object, you are stating to the browser that this script deals directly with numbers and mathematics.

“round” (note lack of capitalization) is a method that rounds off the number that “Math” will soon represent.

“random” (again, note lack of caps) is a method that asks for a random number between 0 and 1. Keep in mind that JavaScript plays in millisections so it’s not as silly as it first seems. There are 1000 choices the script can make.

So, let’s read the line. Return to the script a rounded-off version (Math.round) of the upper_limit (not yet set), times (*) a random number between 0 and 1 (Math.random()). If the upper limit is set to 50, you would get one of 50 different answers, and since the round method rounds up, you’ll never get a zero.

Make a note of where all the parentheses are. The upper limit number and the random number between 0 and 1 are figured first. Then the number is rounded. Remember that from high school algebra? What’s inside the ( ) gets figured first.

That’s the mathematics of it all. But where does the upper limit come from? Why, it’s the function itself! See you next week.

Next Time: The Upper Limit

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Latest Posts

Related Stories