How to get a Random Float in a Range using JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 23, 2022

banner

Photo from Unsplash

Get a Random Float in a Range #

To get a random float in a range:

  1. Use the Math.random() function to get a random number from 0 to 0.999...
  2. Multiply the number by the result of subtracting the min value in the range from the max value.
  3. Add the min value to the result, and call to toFixed() method to round the decimals.
index.js
function getRandomFloat(min, max, decimals) { const str = (Math.random() * (max - min) + min).toFixed(decimals); return parseFloat(str); } console.log(getRandomFloat(1.5, 3.5, 2)); // 👉️ 2.18 console.log(getRandomFloat(1.5, 3.5, 3)); // 👉️ 1.648 console.log(getRandomFloat(1.5, 3.5, 4)); // 👉️ 2.334

We created a reusable function that returns a random float in a range and takes 3 parameters:

  1. The min value in the range
  2. The max value in the range
  3. The number of decimals we want to round the number to

The Math.random function returns a number from 0 up to 1. The number can be 0, but it can't be 1.

Here are some examples.

index.js
console.log(Math.random()); // 👉️ 0.4234243... console.log(Math.random()); // 👉️ 0.8124353... console.log(Math.random()); // 👉️ 0.0043243... // 👇️ returns a number from 0 up to 1.999... console.log(Math.random() * (3.5 - 1.5)); // 👉️ 1.328438... console.log(Math.random() * (3.5 - 1.5)); // 👉️ 0.803458... console.log(Math.random() * (3.5 - 1.5)); // 👉️ 0.734543...
We multiply the random number by the result of subtracting the min value from the max value.

In the examples, the max value in the range is 3.5 and the min value - 1.5. Subtracting the min from the max returns 2.

When multiplied with Math.random, the result could be from 0 (if Math.random returns 0) up to 1.999.

The next step is to add the min value (1.5) to the result to get a float in the range.

We used the Number.toFixed method to format the number to a string with a specific number of decimal places.

The last step is to use the parseFloat function to parse the string into a float.

Here's the complete example.

index.js
function getRandomFloat(min, max, decimals) { const str = (Math.random() * (max - min) + min).toFixed(decimals); return parseFloat(str); } console.log(getRandomFloat(1.5, 3.5, 2)); // 👉️ 1.96 console.log(getRandomFloat(1.5, 3.5, 3)); // 👉️ 2.036 console.log(getRandomFloat(1.5, 3.5, 4)); // 👉️ 3.0045

Further Reading #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.