Categories
JavaScript Answers

How to generate a random number between 2 values to 2 decimals places in JavaScript?

Spread the love

Sometimes, we want to generate a random number between 2 values to 2 decimals places in JavaScript.

In this article, we’ll look at how to generate a random number between 2 values to 2 decimals places in JavaScript.

How to generate a random number between 2 values to 2 decimals places in JavaScript?

To generate a random number between 2 values to 2 decimals places in JavaScript, we can use the Math.floor and Math.random methods.

For instance, we write:

const precision = 100;
const randomNum = Math.floor(Math.random() * (10 * precision - 1 * precision) + 1 * precision) / (1 * precision);
console.log(randomNum)

to call Math.random to generate a number between 0 and 1.

Then we multiply the returned number by (10 * precision - 1 * precision) and add by 1 * precision to return the number in the range we want multiplied by precision.

Then we divide by (1 * precision) to return the number with the precision and range we want.

Therefore, randomNum should be a random number with 2 decimal places since precision is 100.

Conclusion

To generate a random number between 2 values to 2 decimals places in JavaScript, we can use the Math.floor and Math.random methods.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *