JavaScript: Get a random number within a range

📅 April 26, 2017
The Math object in JavaScript provides the random() function that returns a floating point value from 0 to up to but not including 1.

What if we want to grab an integer, say, from 1 to 25 inclusive?

We can do this easily by modifying the random result to our liking.

For this example, we are going to use JavaScript to display a random weather icon on a page.

Suppose we have a subdirectory (named weather) of small icons named 001.png to 025.png sequentially. Our script will pick one at random by generating a random number from 1 to 25 using Math.random().

These are the weathy public domain icons. Notice that each is named sequentially. We can write a script that generates the filename.

Code

Write a test HTML5 file and place the script within the body.

gedit source code.

The trick is the line

var num = Math.floor(Math.random() * 25) + 1;

There are three points combined into one.

  1. Math.random() returns 0 to 0.99999~. We want an integer result such as 2, 3, and 20. To do this, we multiply by 25, which is the upper limit. This gives us something like 10.456344, 2.3445566, or 24.595834.
  2. To remove the floating-point part and keep only the integer, we must pass the result to the Math.floor() function to round down. This now gives us 10, 2, or 24 (from the example above).
  3. We have a problem. The range is 0 to 24. We need 1 to 25, so we add 1 to the result. This gives us the range we need: 1 to 25.

Now that we are generating a valid random number within the range 1 to 25, we need to modify it into a valid filename.

All icons are stored in a directory called weather, so iconFilename will initialize to weather/ (yes, with the forward slash).

The if statement checks the value. If 1 through 9, then two 00’s are prefixed along with the .png filename extension. If not, which assumes 10+, then only one 0 is prefixed. This is because all icon filenames contain three digits. The code as written does not pad to three places.

As an example, here are a few results:

Math.random()     Result
----------------------------
    1             weather/001.png
   10             weather/010.png
   25             weather/025.png

Open the html file in a browser. We should see a random weather icon appear.

003.png chosen at random in the Vivaldi browser.

The text weather/003.png is produced by document.write(iconFilename) for debugging purposes.

We use

document.getElementById("weathericon").src = iconFilename;

to dynamically change the icon shown by the img element, which was given an id of weathericon.

Refresh the browser to see another icon.

F5 refreshes the browser quickly. A different icon should appear, but chances are good that the same icon will be seen.

I Do Not See Any Icons

Always open the browser’s developer tools when writing client-side JavaScript. In Vivaldi, this is found in the Vivaldi menu > Tools > Developer Tools. Have the console open. If there is an error in the JavaScript, then nothing will appear in the browser window, but we can see any error messages here.

Vivaldi’s Developer Tools. If there is an error in the script, then an error message will appear in the Console output along with a line number to indicate which line contains the error. Here, line 19 contains iconfilename instead of iconFilename. This tool helps diagnose scripting errors. If the browser is blank or produces unexpected output, check this first.

That is all for random number generation in JavaScript. Of course, there are other ways to produce the same weather icon output on a web page (an array of filenames, for example). For more information regarding Math.random(), have a look at the Mozilla Developer Network for more information.

Advertisements

,

  1. Leave a comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: