In JavaScript, the Math.random() function is used to generate a pseudo-random floating-point number between 0 (inclusive) and 1 (exclusive). This means the generated number can be any value from 0 up to, but not including, 1.
Example 1: Print a random number
printRandomNumber.js
let randomNumber = Math.random(); console.log(`randomNumber : ${randomNumber}`);
Sample output on run 1
randomNumber : 0.1672875320265117
Sample output on run 2
randomNumber : 0.45151985242188997
Sample output on run 3
randomNumber : 0.5061797545590498
Generating Random Integers Within a Range
To generate a random integer within a specific range (say between min and max, inclusive), you can use the following function:
randNumberWithinRange.js
function getRandomInt(min, max) { min = Math.ceil(min); // Round up the min value to the nearest integer max = Math.floor(max); // Round down the max value to the nearest integer return Math.floor(Math.random() * (max - min + 1)) + min; } console.log(`Random number between 5 and 10 ${getRandomInt(5, 10)}`); console.log(`Random number between 5 and 11 ${getRandomInt(5, 11)}`); console.log(`Random number between 5 and 12 ${getRandomInt(5, 12)}`);
Sample Output
Random number between 5 and 10 9 Random number between 5 and 11 11 Random number between 5 and 12 7
· Math.random() generates a random floating-point number between 0 and 1.
· This value is then multiplied by (max - min + 1), which represents the total number of possible integers between min and max, inclusive.
· Math.floor() is used to round down the result to the nearest integer, ensuring it falls within the range.
· Finally, min is added to shift the range from [0, (max - min)] to [min, max].
Generating Random Decimals Within a Range
To generate a random decimal number within a specific range, you can use the following function.
function getRandomDecimal(min, max) { return Math.random() * (max - min) + min; }
randDecimalWithinRange.js
function getRandomDecimal(min, max) { return Math.random() * (max - min) + min; } console.log(`Random decimal between 5 and 10 : ${getRandomDecimal(5, 10)}`); console.log(`Random decimal between 5 and 11 : ${getRandomDecimal(5, 11)}`); console.log(`Random decimal between 5 and 12 : ${getRandomDecimal(5, 12)}`);
Output
Random decimal between 5 and 10 : 5.487781544915245 Random decimal between 5 and 11 : 6.190685752138041 Random decimal between 5 and 12 : 8.538375936112882
· Math.random() generates a random floating-point number between 0 and 1.
· This value is then multiplied by (max - min), which scales the random number to the desired range.
· Finally, min is added to shift the range from [0, (max - min)] to [min, max).
Previous Next Home
No comments:
Post a Comment