Math random JavaScript Generate the Whole number

  • by

JavaScript Math Random method returns a random number (floating) between 0 (inclusive),  and 1 (exclusive). To get the integer number you have to use Math.floor() function with it.

Example: How to use Math.random()

<!DOCTYPE html>
<html>
<body>

	<p id="result"></p>

	<script>
	document.getElementById("result").innerHTML = Math.random();
	</script>

</body>
</html>

Output:

Math random JavaScript

Q: How to Generate Random Whole Numbers with JavaScript?

Answer: It’s easy and useful to generate random decimals or whole numbers. See below steps to do get the whole number:-

  1. Use Math.random() to generate a random decimal.
  2. Multiply that random decimal by 100 or any number.
  3. Use another function, Math.floor() to round the number down to its nearest whole number.
Math.floor(Math.random() * 100);

Complete Example and Programming code:-

<!DOCTYPE html>
<html>
<body>

	<p id="result"></p>

	<script>

	function randomWholeNum() {
  	// Only change code below this line.
  	return Math.floor(Math.random() * 100);
	}

	document.getElementById("result").innerHTML = randomWholeNum();
	</script>

</body>
</html>

How to return random integers between the given range?

Answer: See below code for Returns a random integer from.

0 to 9

Math.floor(Math.random() * 10);

0 to 10

Math.floor(Math.random() * 11);

0 to 100

Math.floor(Math.random() * 101);
Math.floor(Math.random() * 101);

10 to 100

<!DOCTYPE html>
<html>
<body>

	<p id="result"></p>

	<script>

	function randomWholeNum() {
	var min=10; 
    var max=100;  
    var random = Math.floor(Math.random() * (+max - +min)) + +min;
    
  	return random; 
	}

	document.getElementById("result").innerHTML = randomWholeNum();
	</script>

</body>
</html>

Supported Browsers: The browsers supported by JavaScript Math.random() function are listed below:

  • Google Chrome
  • Internet Explorer
  • Firefox
  • Opera
  • Safari

Do comment if you have any doubts and suggestions on this tutorial.

Note: The All JS Examples codes are tested on the Safari browser (Version 12.0.2) and Chrome.
OS: macOS 10.14 Mojave
Code: HTML 5 Version

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.