
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to generate a random number in JavaScript?
Generating a random number
To generate a random number, Math.random() is used. We can even generate a number between specified numbers such as between 1 and 10, between 0 and 100, etc. Let's discuss it using an example.
syntax
Math.random();
Example
In the following example, using Math.random() function inside a Math.floor() function, which results in integer values, a random number is found out between the numbers 1 and 100. Since we have used an expression (Hl - Ll + 1), where Hl is the higher limit and Ll is the lower limit, inside the Math.floor() function, a random value can even include 1 and 100. if we want to exclude the extremes, remove 1 from the above-mentioned expression so that the expression looks like (Hl - Ll).
<html> <body> <p>Generating a random integer</p> <input type = "button" onclick="document.getElementById('random').innerHTML = randIntr(1,100)" value = "generate"> <p id="random"></p> <script> function randIntr(Hl, Ll) { return Math.floor(Math.random() * (Hl - Ll + 1) ) + Ll; } </script> </body> </html>
Once the function is executed, the following will be displayed on the screen.
Once we click on the button generate we will get a random number as shown in the output.
Output
- Related Questions & Answers
- How to generate a random number in C++?
- C++ program to generate random number
- How to generate 6-digit random number in MySQL?
- Generate random string/characters in JavaScript?
- Generate Random Float type number in Java
- Generate Random double type number in Java
- How to generate random whole numbers in JavaScript in a specific range?
- Java Program to generate random number with restrictions
- Java Program to generate a random number from an array
- How to generate random numbers between two numbers in JavaScript?
- Generate random characters and numbers in JavaScript?
- How can I generate random number in a given range in Android?
- JavaScript to generate random hex codes of color
- How to generate a random BigInteger value in Java?
- How to generate random colors in Matplotlib?