Why is it when I print/display the result of
eval("11.05") + eval("-11")
it comes out as 0.05000000000000071 instead of the expected 0.05. Is there something I am missing?
Why is it when I print/display the result of
eval("11.05") + eval("-11")
it comes out as 0.05000000000000071 instead of the expected 0.05. Is there something I am missing?
This has nothing to do with eval
. In fact, this is what happens if you type in a console 11.05 - 11
:
This is a consequence of how programming languages store floating-point numbers; they include a small error. If you want to read more about this, check this out.
This has nothing to do with eval
(which you should avoid).
You get the same problem with 11.05 - 11
.
This is just the usual floating point problem
As others have indicated, this is a floating point problem and has nothing to do with eval
. Now for eval
: you can easy avoid it here, using:
Number("11.05") + Number("-11");
To avoid the faulty outcome you could use toPrecision
:
(Number("11.05") + Number("-11")).toPrecision(12);
// or if you want 0.05 to be the outcome
(Number("11.05") + Number("-11")).toPrecision(1);
The function eval
is absolutely innocent here. The culprit is floating-point operation. If you do not expect a large number of numbers after the decimal, you may limit. But you can not avoid it.