jQuery and ASP.NET

August 5, 2010

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



'Like' us on our FaceBook page if you find this blog useful. Thanks!


Did you like this post?
kick it on DotNetKicks.com Save on Delicious
subscribe via rss subscribe via e-mail
print this post follow me on twitter


About The Author

Suprotim Agarwal, ASP.NET Architecture MVP 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 has also written an EBook 51 Recipes using jQuery with ASP.NET Controls.

Follow him on twitter @suprotimagarwal

comments

2 Responses to "Generate Random Numbers Within a Range using JavaScript"
  1. Ben Archer said...
    March 2, 2011 6:12 PM

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

    benjamin.morse.archer@gmail.com

  2. Suprotim Agarwal said...
    March 2, 2011 9:18 PM

    Ben: In that case use the following:

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

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

 

Copyright © 2009-2011 All Rights Reserved for DevCurry.com by Suprotim Agarwal | Terms and Conditions