Avoiding problems with JavaScript's weird decimal calculations

后端 未结 6 715
我寻月下人不归
我寻月下人不归 2020-11-29 05:13

I just read on MDN that one of the quirks of JS\'s handling of numbers due to everything being \"double-precision 64-bit format IEEE 754 values\" is that when you d

6条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-29 05:38

    In situations like these you would tipically rather make use of an epsilon estimation.

    Something like (pseudo code)

    if (abs(((.2 + .1) * 10) - 3) > epsilon)
    

    where epsilon is something like 0.00000001, or whatever precision you require.

    Have a quick read at Comparing floating point numbers

提交回复
热议问题