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
?
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
?
To not deal with many 0s, use this variant:
MarkG and Lavamantis offered a much better solution than the one that has been accepted. It's a shame they don't get more upvotes!
Here is the function I use to solve the floating point decimals issues also based on MDN. It is even more generic (but less concise) than Lavamantis's solution:
Use it with:
Compared to Lavamantis's solution, we can do...
Use
Math.round(num * 100) / 100
Use something like this "parseFloat(parseFloat(value).toFixed(2))"
There are a couple of ways to do that. For people like me, the Lodash's variant
Usage:
If your project uses jQuery or lodash, you can also find proper
round
method in the libraries.Update 1
I removed the variant
n.toFixed(2)
, because it is not correct. Thank you @avalanche1Here is a prototype method: