Strange result with floating point addition

前端 未结 4 1613

Why is it when I print/display the result of

eval(\"11.05\") + eval(\"-11\")

it comes out as 0.05000000000000071 instead of the expecte

相关标签:
4条回答
  • 2020-12-11 23:41

    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.

    0 讨论(0)
  • 2020-12-11 23:47

    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.

    0 讨论(0)
  • 2020-12-11 23:50

    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

    0 讨论(0)
  • 2020-12-11 23:58

    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);
    
    0 讨论(0)
提交回复
热议问题