How to get a Random Float in a Range using JavaScript

avatar

Borislav Hadzhiev

Thu Oct 28 20212 min read

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 our examples the max value in the range is 3.5 and the min value - 1.5. When you subtract the min from the max you get 2 back.

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 then use 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 #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee