Before discussing the main topic, let us see how to print a random number in plain JavaScript. If you don’t know already there is this Math.random() function available in JavaScript to generate random numbers. But, there is a problem it will not return a whole number instead it will return a float number. So first, let’s write a simple snippet to print a whole random number.
1. JavaScript snippet to print a random number:
1 2 |
var rand_num = Math.floor(Math.random() * 1000); console.log(rand_num); |
The above snippet will print a random number in the JavaScript console.
Now, we know how to print a random number, but what actually we need is, we have to print a random number between two values, so let’s write another example:
2. JavaScript to print a random number between two given values:
1 2 3 4 5 |
var min = 10; var max = 15; var rand_num = Math.floor(Math.random() * (max - min + 1)) + min; console.log(rand_num); |
This script above one will generate a random number between 10 and 15. So that’s it, you know now!.
To explore this more, I am giving another working demo & example script of both the above scenarios.
Here is the entire script for you to explore:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
<!DOCTYPE Html> <html> <head> <title>Print Random numbers using JavaScript - Tutorialsmade.com</title> <script type="text/javascript"> function randNum(){ var rand_num = Math.floor(Math.random() * 1000); var result_div = document.getElementById('rand_num_result'); result_div.innerHTML = "Random Number: "+ rand_num; } function randNumBetweenTwoVal(){ var min = parseInt(document.getElementById('start').value); var max = parseInt(document.getElementById('end').value); var rand_num = Math.floor(Math.random() * (max - min + 1)) + min; var result_div = document.getElementById('rand_bet_result'); result_div.innerHTML = "Random Number between: "+ rand_num; } </script> </head> <body> <h2>Print a Random number in JavaScript!</h2> <button onclick="randNum()">Click Button to Print a Random Number</button> <br><br> <div id="rand_num_result"></div> <br> <h2>Print Random numbers between two values in JavaScript! - Tutorialsmade.com</h2> Start Range: <input type="number" id="start" min="1" value="45" max="1000" /> End Range: <input type="number" id="end" min="2" value="50" max="1000" /> <button onclick="randNumBetweenTwoVal()">Print</button><br><br> <div id="rand_bet_result"></div> </body> </html> |
You can also see the demo here: