Round to at most 2 decimal places (only if necessary)

stinkycheeseman picture stinkycheeseman · Aug 6, 2012 · Viewed 2.7M times · Source

I'd like to round at most 2 decimal places, but only if necessary.

Input:

10
1.7777777
9.1

Output:

10
1.78
9.1

How can I do this in JavaScript?

Answer

Brian Ustas picture Brian Ustas · Aug 6, 2012

Use Math.round(num * 100) / 100

Edit: to ensure things like 1.005 round correctly, we use

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