The Math.random function in JavaScript allows you to generate a pseudo-random decimal number between 0 inclusive and 1 excluded.

Let’s immediately make an example of using the following function.

JavaScript Math random – first example

So, try clicking on the button below ‘Generate random’.

It generates a random number between 0 and 100 and if you try to click on the button again clearly the number changes. So from time to time a new number is generated.

Implementation

To implement this example, let’s develop a function that calls:

  • the Math.random() function, that generates a floating point pseudo-random number between 0 and 1, with 1 not included.
  • the Math.round() functions that returns the value of a number approximated to the nearest integer.

So, to generate the random numbers from 0 to 100 we use:

Banner Pubblicitario


    number = Math.round(Math.random () * 100);

With the Math.round() function we round to the integer.

We could also use the Math.floor() function in this way:



    number = Math.floor(Math.random () * 100);

But it generates numbers from 0 to 99 and therefore to have numbers from 0 to 100 we would have to write: Math.floor (Math.random ( ) * 101).

So here’s the JavaScript function:



function randomNumber() {
    number = Math.round(Math.random() * 100);
    document.getElementById("random").innerHTML ="Random number " + number ;
}

We then create a button-type input box for the button in html, to which we associate the onclick event that calls the random function ().

<input type="button" onclick="randomNumber()" value="Generate number random">
<div id="random"></div>

So for example if I want to generate the numbers from 1 to 6 I write: Math.round (Math.random () * 5) +1;

JavaScript Math random – second example

In this second example we ask the user how many random numbers he wants to generate, transcribing them into an input box. So we click on the button and generate them.

Banner pubblicitario
Write in the box below how many numbers you want to generate,

Algorithm procedure

We proceed by generating the Math.random function to generate the random numbers.

First we check that the number entered in the field how many numbers to generate is between 1 and 100 with an if. If it is, we proceed to generate the numbers, otherwise we give a warning message to the user to enter a value between 1 and 100.

We use the parseInt function to return an integer anyway.

So with a simple for loop I generate the numbers and print them separated by a comma.



function randomNumbers() {
  n = parseInt(document.getElementById("howMany").value);

  if (n > 0 && n <= 100) {
    str = "";
    for (i = 0; i < n; i++) {
         num = Math.round(Math.random()*100 + 1);
         if (i > 0) {
            str += ", ";
         }
         str += num;
     }
     document.getElementById("random").innerHTML ="Numbers generated: " + str;
     } else 
    document.getElementById("random").innerHTML ="Insert a number > 0 e < 100";
   }
}

Here is the html code:





Conclusion

These are just some simple examples of using the Math.random function in JavaScript, in the next lesson we will study other functions.

Some useful links

Indice argomenti tutorial JavaScript