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

2 comments:

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

    benjamin.morse.archer@gmail.com

    ReplyDelete
  2. Ben: In that case use the following:

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

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

    ReplyDelete