Home >>Javascript Programs >Generate random number within a range in JavaScript
This article will describes you how to generate a random number by using JavaScript. A number whose outcome is unpredictable and generated by a process is called Random Number. By using the function Math.random(), we can achieve this number. Sometimes, we need to generate a random number between a range. Math.random() function generates floating numbers between 0 and 1.
Math.random() function: It returns a pseudo-random number between range 0 and 1. It can be scaled the random number between the desired range.
Here, is a simple program to do so to generate the random number between a range by using the in-built function Math.random().
Let's take an example:
<!DOCTYPE html> <html> <head> <title>How to generate random number within a range in JavaScript? </title> </head> <body> <script> // Function to generate random number function randomNumber(min, max) { return Math.random() * (max - min) + min; } document.write("Random Number between 1 and 10: ") // Function call document.write( randomNumber(1, 10) ); </script> </body> </html>
Math.floor() function: The Math.floor() function helps you to round off the number to its nearest integer towards the lesser value.
Let's take an example:
<!DOCTYPE html> <html> <head> <title>How to generate random number within a range in JavaScript? </title> </head> <body> <script> // Function to generate random number function randomNumber(min, max) { return Math.floor(Math.random() * (max - min) + min); } document.write("Random Number between 1 and 50: ") // Function call document.write( randomNumber(1, 50) ); </script> </body> </html>