snippetjavascriptCritical
How to round to at most 2 decimal places, if necessary
Viewed 0 times
hownecessaryroundplacesdecimalmost
Problem
I'd like to round at most two decimal places, but only if necessary.
Input:
Output:
How can I do this in JavaScript?
Input:
10
1.7777777
9.1Output:
10
1.78
9.1How can I do this in JavaScript?
Solution
Use
Or to be more specific and to ensure things like 1.005 round correctly, use Number.EPSILON :
Math.round() :Math.round(num * 100) / 100Or to be more specific and to ensure things like 1.005 round correctly, use Number.EPSILON :
Math.round((num + Number.EPSILON) * 100) / 100Code Snippets
Math.round(num * 100) / 100Math.round((num + Number.EPSILON) * 100) / 100Context
Stack Overflow Q#11832914, score: 5568
Revisions (0)
No revisions yet.