How to round to at most 2 decimal places, if necessary

Created by Brian UstasLinked to 21.9m issues across 56 teams

tl;dr

To round a number to at most two decimal places, you can use the Math.round() method. This method takes a number as an argument and returns the rounded value. For example, if you want to round the number 1.005 to two decimal places, you would use the following code:

Math.round(1.005 * 100) / 100

This will return the rounded value of 1.01.

If you want to ensure that the number is rounded correctly, you can use the Number.EPSILON constant. This constant is a small number that is used to ensure that the rounding is accurate. To use it, you would use the following code:

Math.round((1.005 + Number.EPSILON) * 100) / 100

This will also return the rounded value of 1.01.