3

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?

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • 1
    This is not a `eval` issue, its due to floating point arithmetic. See [this question](http://stackoverflow.com/questions/588004/is-javascripts-math-broken) – The Scrum Meister Jun 14 '11 at 05:54

4 Answers4

5

This has nothing to do with eval. In fact, this is what happens if you type in a console 11.05 - 11: enter image description here

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.

Gabi Purcaru
  • 30,940
  • 9
  • 79
  • 95
3

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

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
1

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);
KooiInc
  • 119,216
  • 31
  • 141
  • 177
0

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.

Kangkan
  • 15,267
  • 10
  • 70
  • 113