Home JavaScript Example Javascript Program to Generate a Random Number

Javascript Program to Generate a Random Number

by anupmaurya
3 minutes read

In this example, you will learn to generate a random number in JavaScript.

For this example, we are using two pre-defined libraries as follows:

In JavaScript, you can generate a random number with the Math.random() function.

Math.random() returns a random floating-point number ranging from 0 to less than 1 (inclusive of 0 and exclusive of 1)

Generate a Random Number

// generating  a random number
const a = Math.random();
console.log(a);

Output

0.5856407221615856

Here, we have declared a variable a and assigned it a random number greater than or equal to 0 and less than 1.

Get a Random Number between 1 and 20

// generating a random number
const a = Math.random() * (20-1) + 1
console.log(`Random value between 1 and 20 is ${a}`);

Output

Random value between 1 and 20 is 12.392579122270686

This will show a random floating-point number greater than 1 and less than 20.

To get whole numbers, we can use:

  • Math.floor() → to round down
  • Math.ceil() → to round up
  • Math.round() → to nearest number

Here Let understand by using Math.floor(), It is a function in JavaScript that is used to round off the number passed as a parameter to its nearest integer in the Downward direction of rounding i.e towards the lesser value.

SYNTAX

Math.floor(value)

EXAMPLE

This example generate random integer number between 1(min) and 100(max).

// Function to generate random number
function randomNumber(min, max) {
	return Math.floor(Math.random() * (max - min) + min);
}

document.write("Random Number between 1 and 100: ")

// Function call
document.write( randomNumber(1, 100) );								

OUTPUT

Random Number between 1 and 100: 87

EXAMPLE
This example generate random whole number between 1(min) and 10(max) both inclusive.

// Function to generate random number
function randomNumber(min, max) {
	min = Math.ceil(min);
	max = Math.floor(max);
	return Math.floor(Math.random() * (max - min + 1)) + min;
}

document.write("Random Number between 1 and 10: ")

// Function call
document.write( randomNumber(1, 10) );

OUTPUT

Random Number between 1 and 10: 3

You may also like

Adblock Detected

Please support us by disabling your AdBlocker extension from your browsers for our website.