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;

i.e.

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

Here’s the entire code:

<html xmlns="http://www.w3.org/1999/xhtml" >
<
head>
<
title>Random Number in JavaScript</title>
<
script type="text/javascript">
var
randomNumber = Math.floor(Math.random() * 51) + 25;
document.write("<p>" + randomNumber + "</p>");
</script>
</
head>
<
body>
</
body>
</
html>

See a Live Demo






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.

2 comments:

Anonymous said...

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

benjamin.morse.archer@gmail.com

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!