Generate Random Numbers Within a Range using JavaScript

A formula for generating a random number within a given range using JavaScript is as follows:

Math.floor(Math.random() * (UpperRange - LowerRange + 1)) + LowerRange;

So to generate a random number between 25 and 75, the equation would be

Math.floor(Math.random() * (75-25+1)) + 25;


Math.floor(Math.random() * 51) + 25;

Here’s the entire code:

<html xmlns="" >
title>Random Number in JavaScript</title>
script type="text/javascript">
randomNumber = Math.floor(Math.random() * 51) + 25;
document.write("<p>" + randomNumber + "</p>");

See a Live Demo

Will you give this article a +1 ? Thanks in advance

About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal.


Anonymous said...

Thanks! What if I want it to be equal than or greater to X, but less than Y?

Suprotim Agarwal said...

Ben: In that case use the following:

Math.floor(Math.random()*(Y-X)) + X;

Although I have not tested it, but it should work!