Generate a random float within a specific range in JavaScript
This post will discuss how to generate a random float value within a specific range in JavaScript.
To generate a random float in JavaScript, we can use the Math.random() function. This function returns a floating-point, pseudo-random number that is greater than or equal to 0 and less than 1, with approximately uniform distribution over that range. We can scale and manipulate this value to get a random number within our desired range. For example, if we want to generate a random float between 5 and 10, we can do this:
|
1 2 3 4 5 6 7 8 9 10 11 |
function getRandomFloat(min, max) { return Math.random() * (max - min) + min; } let min = 5; // the lower bound of the range let max = 10; // the upper bound of the range // This will generate a random number between `min` and `max` let num = getRandomFloat(min, max); console.log(num); // a possible output is 7.644939389567394 |
This function return a random float between min (inclusive) and max (exclusive). If we want to round the random float to a certain number of decimal places, we can use the toFixed() function. For example, if we want to round the random float to 2 decimal places, we can do this:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
function getRandomFloat(min, max, decimals) { let randomFloat = Math.random() * (max - min) + min; let roundedFloat = randomFloat.toFixed(decimals); return roundedFloat; } let min = 5; let max = 10; // This will generate a random floating-point string value // between `min` and `max` with 2 decimal places let num = getRandomFloat(min, max, 2); console.log(num); // a possible output is "7.64" |
Note that the toFixed() function returns a string, not a number. If we want to convert the string returned by toFixed() back to a number, we can use the parseFloat() function or the unary plus operator (+). They parses a string into a floating-point number. Here’s an example of how we can achieve this:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
function getRandomFloat(min, max, decimals) { let randomFloat = Math.random() * (max - min) + min; let roundedFloat = randomFloat.toFixed(decimals); let parsedFloat = parseFloat(roundedFloat); // or +roundedFloat; return parsedFloat; } let min = 5; let max = 10; // This will generate a random number between `min` and `max` with 2 decimal places let num = getRandomFloat(min, max, 2); console.log(num); // a possible output is 7.64 |
That’s all about generating a random float value within a specific range in JavaScript.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)