In this Javascript program we will cover how to generate random numbers. We all know to generate random numbers we will use Math package with Math.random() method.
Let's write program
<script>
|
Generally Math.random() generate random numbers with given range, normally 0 to 1. So this will generate below output without given range.
Output:
0.39122962255698623 |
Generate Random Numbers with Given range
Syntax:
Math.random() * (highestNumber - lowestNumber) + lowestNumber |
Write example to generate random numbers with in given range
<script> // a program for random number between 15 and 100
|
Output
Random number between 15 and 100 = 33.30355790059883 |
Generate Random Integers or whole numbers in Javascript
Always Math.random() generate decimal numbers, to generate integer or whole numbers we can use Math.floor() method.
Syntax:
Math.floor(Math.random() * (highestNumber - lowestNumber)) + lowestNumber |
Example
<script> // a program for random number Integer between 15 and 100
|
Output:
Random number between 15 and 100 = 16 |