JavaScript - Math - Random Method Example - Dirask
JavaScript - Math - Random Method Example - Dirask
1. Documentation Edit
Syntax Math.random()
1 /*
2 inclusive min (result can be equal to min value)
3 exclusive max (result will not be to max value)
4 */
5 function randomizeFloat(min, max) {
6 if (max == null) {
7 if (min <= 0) {
8 throw new Error('Max value must be positive.');
9 }
https://dirask.com/posts/JavaScript-Math-random-method-example-x1R6G1 1/3
25/08/2020
10
11 max = (min == null ? Number.MAX_VALUE : min);
12 min = 0.0;
13 }
14
15 if (min >= max) {
16 throw new Error("Incorrect arguments.");
17 }
18
19 return min + (max - min) * Math.random();
20 }
21
22 // Example:
23
24 console.log(randomizeFloat()); // 1.67319916301163e+308
25 console.log(randomizeFloat(5)); // 2.7593705936801918
26 console.log(randomizeFloat(10, 80)); // 37.54521514384005
27 console.log(randomizeFloat(-50, 50)); // -30.632843429520975
https://dirask.com/posts/JavaScript-Math-random-method-example-x1R6G1 3/3