Syntax
First, the systax.
Math.random()
The random() method is one of the many methods of "Math" object. The function returns a floating-point ranging from 0 to less than 1.
Here’s an example.
<script>
let rndValue = Math.random();
document.write (rndValue);
</script>
The method returns a random number in decimal values or floating number.
You can round off the random floating number using another "Math" method called round().
let rndValue = Math.round(Math.random()); document.write (rndValue);
Random numbers between 0 and 50
Now, lets see how we can generate a random number in a given range between 0 and 50.
<body> <input type='button' id='bt' value='Generate Number' onclick='generate_random()' /> <p id='result'></p> </body> <script> let generate_random = () => { // generate random number between 0 and 50. let rndValue; rndValue = Math.floor((Math.random() * 50)); let p = document.getElementById('result'); p.innerHTML = rndValue; } </script>
👉 You may also like this. Use Math.sign() method to check if a given number is negative or positive
Generate Random numbers between 1 and 10
In the above example, the random() method returned numbers 0 and 50. You can ignore the Zero (0) and a generate number between 1 and a maximum number, like 1 to 10.
<body> <input type='button' id='bt' value='Generate Number' onclick='generate_random()' /> <p id='result'></p> </body> <script> let generate_random = () => { // generate random number between 1 and 10. let rndValue; rndValue = Math.floor((Math.random() * 10) + 1); let p = document.getElementById('result'); p.innerHTML = rndValue; } </script>
Fun with Math.random() Method
Let’s have some fun with the random numbers that we’ll generate. I’ll use the random number to get the ASCII code of a character (or alphabet) in a given string (any string).
<body> <input type='button' id='bt' value='Click it' onclick='generate_random()' /> <p id='result'></p> </body> <script> let generate_random = () => { let rndValue; rndValue = Math.floor((Math.random() * 10)); let p = document.getElementById('result'); p.innerHTML = 'Arun Banik'.charCodeAt(rndValue) + ' ' + 'Arun Banik'.charAt(rndValue); } </script> </html>
The method Math.random() works with all modern browsers including Internet Explorer.