How to Create a Random Number in Javascript

I’ve been working with PHP for some time now, and I’ve become spoiled with the rand() function for generating random numbers. It’s so simple - pass a min, pass a max, and get the number you want.

While I was working on various game-related scripts this weekend, I was left wondering how to create a random number in Javascript. It’s not quite as simple as the rand() function - we’ll have to go back to the old C-style random number generation.

The Math Object and Random Numbers

Javascript comes with a built-in random number generator as part of the Math object. This Math object does a number of calculations - trig functions (sine, cosine, and tangent), rounding, logarithms, exponents, etc.

To use the Math class to generate a random number, you begin with the random method.

Math.random();

This method returns a random value - between 0 and 1.

How Can I Make a Useful Random Number?

If you’ve ever programmed in C/C++, you’ll know what to do. If you’re used to working with something like PHP - which comes with an intelligent built-in random number generator - you may be left in the dark.

How can you take a random decimal - between 0 and 1 - and turn it into a random number between, say, 1 and 100?

The answer is simple - math. You need to multiply the random() result to get a certain sized range and then use addition to start the range at the right number.

Let’s say you multiply the result of Math.random() by 10.

Math.random() * 10

Since the results of Math.random() are between 0 and 1, the results of this statement will be 0 to 10. The minimum result is (0 * 10 = 0) and the highest result is (1 * 10 = 10).

If you were to only look at the whole number part of the result, you would get a range of 0 to 9. In actuality, the result of Math.random() is never 0 or 1, so the above statement won’t give you a result of 10.

Therefore we can use the whole number portion of the result to get a random integer - 0 to 9.

How Do We Get a Whole Number?

Simple. Use the floor method of the Math class. Math.floor returns the whole number portion of a float/decimal.

Math.floor(1.45); //  Result is 1

Simply pass a float/decimal to the Math.floor method, and it will return the integer portion of that number. If you’re working with negative numbers, it will always round down. Keep that in mind. For positive numbers, it’s simply a truncation function.

To get a random integer, we simply pass the result of Math.rand() to Math.floor().

Math.floor( Math.rand() );

What If My Random Set Doesn’t Start at 0?

Here’s the last piece of the random puzzle.

You can determine the size of your random number set with multiplication. The coefficient you use (like we used 10 before) determines the range your random number can be in.

Math.floor( Math.rand() * 10); // 10 Numbers, 0-9
Math.floor( Math.rand() * 5); // 5 Numbers, 0-4
Math.floor( Math.rand() * 100); // 100 Numbers, 0-99

If the set you want to create a random number from doesn’t start with 0, you simply use addition to get what you want.

Let’s say you want a random number from 101-150. Your set contains 50 numbers, and it starts with 101.

(Math.floor( Math.rand() * 50)) + 101; // 101 - 150

The basic statement - Math.floor( Math.rand() * 50) - returns a value between 0 and 49. We want to offset that by 101 places and we’ll have our desired random set - 101 to 150.

At this point, you should have a general equation you can use for generating random numbers from any given set. Take Math.rand(), apply a coefficient to determine the size of the random number set, and then use addition to offset that number to your desired starting point.

(Math.floor( Math.rand() * setSize)) + setOffset;

Now go find something useful to use these random numbers for.


Bookmark and Share:
These icons link to social bookmarking sites where readers can share and discover new web pages.

  • Digg
  • Furl
  • del.icio.us
  • StumbleUpon
  • MisterWong
  • DZone
  • Technorati

Tags: , , , ,

7 Comments to “How to Create a Random Number in Javascript”

  1. Justin said this on

    you should make this into a tiny little helper function

  2. Walkere said this on

    That’s a good idea. In fact I think I’ll go do that right now…

  3. Javascript Function: Random Number Generator | Web Cash said this on

    […] I wrote a short article on generating random numbers in Javascript. The Javascript random number generator is similar to C/++ - it gives you a random number from 0 to […]

  4. javascript random number generator » position:relative - a Web and Now blog said this on

    […] the Web Cash blog wrote an article about random numbers in Javascript. Both articles are similar and I bet they would […]

  5. eXanock said this on

    Thanks for the nice tutorial :D

    I’m currently learning PHP. I feel that I’m beginning to master the language rather well and have decided to learn JavaScript as I think it’s essential knowledge for anyone who wants to be a professional web-programmer.

  6. Walkere said this on

    eXanock, I feel the same way. I’ve been working with PHP for a while now, and I finally decided to learn some Javascript so that I can implement Ajax in some applications.

    I dislike the unpredictable nature of Javascript - since it’s worked out on the client side - but you need some level of Javascript for most modern projects.

  7. How to Create a Useful Random Number in Javascript - Tutorial Collection said this on

    […] View Tutorial No Comment var addthis_pub=”izwan00″; BOOKMARK This entry was posted on Monday, June 8th, 2009 at 2:19 am and is filed under Javascript Tutorials. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site. […]

Leave a Reply