15
NoJS
6y

0.1 + 0.2 ≠ 0.3

That's JavaScript.

And it caused me two days of agony and irrational bug fixing.

Comments
  • 15
    That’s just floats for you.
  • 8
  • 1
    Practical hack - when comparing two floating point numbers, don't compare them using the equality operator. Instead, define a maximum error that your application is able to tolerate and check if the absolute value of the difference between the two floats is lesser than that error.

    This does require introducing an error term in your calculations and can get kinda messy in heavy number crunching scenarios - but again, that's the price you pay for the enormous range of floats.

    There are other ways to deal with this (converting equations to nicer intervals, rearranging terms, fixed precision arithmetic, etc) but for most applications, this is the simplest one I've found and it usually just works.
  • 1
    @RememberMe
    Use Decimal/Numeric data types or if you want to make you life harder you can do:
    int whole;
    int fraction;
  • 0
    Dude no... That's not JavaScript, that's floating-point which is present in every single programming language.

    Learn how to use them correctly and understand how numbers are being encoded by your computer and you will be fine.

    http://floating-point-gui.de/basic
Add Comment