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
?
A simpler ES6 way is
This pattern also returns the precision asked for.
ex:
You can use
I found this over on MDN. Their way avoids the problem with 1.005 that was mentioned.
Consider
.toFixed()
and.toPrecision()
:http://www.javascriptkit.com/javatutors/formatnumber.shtml
If you are using lodash library, you can use the round method of lodash like following.
Eg:
Use this function
Number(x).toFixed(2);
You should use:
No one seems to be aware of
Number.EPSILON
.Also it's worth noting that this is not a JavaScript weirdness like some people stated.
That is simply the way floating point numbers works in a computer. Like 99% of programming languages, JavaScript doesn't have home made floating point numbers; it relies on the CPU/FPU for that. A computer uses binary, and in binary, there isn't any numbers like
0.1
, but a mere binary approximation for that. Why? For the same reason than 1/3 cannot be written in decimal: its value is 0.33333333... with an infinity of threes.Here come
Number.EPSILON
. That number is the difference between 1 and the next number existing in the double precision floating point numbers. That's it: There is no number between1
and 1 +Number.EPSILON
.EDIT:
As asked in the comments, let's clarify one thing: adding
Number.EPSILON
is relevant only when the value to round is the result of an arithmetic operation, as it can swallow some floating point error delta.It's not useful when the value comes from a direct source (e.g.: literal, user input or sensor).