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, ASP.NET Architecture MVP (Microsoft Most Valuable Professional) works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He is the Editor of a Developer Magazine called DNC Magazine. He has also written two EBooks 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!