C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
JavaScript Math random() methodThe JavaScript math random() method returns the random number between 0 (inclusive) and 1 (exclusive). Syntax
The random() method is represented by the following syntax: Math.random() Return
The random number between 0 (inclusive) and 1 (exclusive). JavaScript Math random() method example
Here, we will understand random() method through various examples. Example 1Let's see an example to find out the random number between 0 and 1. <script> document.writeln(Math.random()) </script> Output: 0.9118351487222218 Example 2Let's see an example to find out the random number between two values.
<script>
function getRandom(min, max) {
return Math.random() * (max - min) + min;
}
document.writeln(getRandom(3,5));
</script>
Output: 3.9030538241130746 Example 3Let's see an example to find out the random integer number between two values.
<script>
function getRandom(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min)) + min;
}
document.writeln(getRandom(3,5));
</script>
Output: 3
Next TopicJavaScript Math
|