To generate a random number, we use the Math.random[] function. This method returns a floating-point number in the range 0 [inclusive] to 1 [exclusive]. To generate random numbers in different range, we should define the minimum and maximum limits of the range. Please follow the second syntax below for this.
To generate random integers, you can follow the third and fourth syntax discussed below.
As the Math.random[] method gives us a random floating point number so to convert the result into an integer, we need to apply some basic math. Please follow the below syntaxes.
Syntax
Following is the syntax for generating a random number between two numbers −
Generate a random number between 0 [inclusive] and 1 [exclusive].
MMath.random[]
Generate a random number between two numbers.
Math.random[] * [max-min] + min];
Generate a random integer between two numbers min and max [both min and max are inclusive].
Math.floor[Math.random[] * [[max-min]+1] + min];
Generate a random integer between two numbers min and max [the min is inclusive, and the max is exclusive].
Math.floor[Math.random[] * [max-min] + min];
Here min and max are the start and end numbers between those we want to generate the random numbers.
Example 1
Generate a random number between 0 [inclusive] and 1 [exclusive].
In the example below, we generate a random number between 0 and 1. Here 0 in inclusive and 1 is exclusive.
Genrate a random number between 0 [inclusinve] and 1 [exclusinve] var random = Math.random[]; document.getElementById["result"].innerHTML = random;
Example 2
Generate many random numbers between 0 [inclusive] and 1 [exclusive].
In the example below, we generate 10 random numbers between 0 and 1. Here 0 is inclusive and 1 is exclusive.
Genrate 10 random numbers between 0 [inclusinve] and 1 [exclusinve] for[var i =0; i .5];.