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
?
In general, rounding is done by scaling:
round(num / p) * p
Using the exponential notation handles rounding of +ve numbers, correctly. However, this method fails to round -ve edge cases correctly.
Here, also is one function I wrote to do arithmetic rounding correctly. You can test it yourself.
For me Math.round() was not giving correct answer. I found toFixed(2) works better. Below are examples of both:
Try this light weight solution:
It may work for you,
to know the difference between toFixed and round. You can have a look at Math.round(num) vs num.toFixed(0) and browser inconsistencies.
Easiest way:
+num.toFixed(2)
It converts it to a string, and then back into an integer / float.
If you happen to already be using the d3 library, they have a powerful number formatting library: https://github.com/mbostock/d3/wiki/Formatting
Rounding specifically is here: https://github.com/mbostock/d3/wiki/Formatting#d3_round
In your case, the answer is: