Adding Floating-Point Decimals for Fun and Profit

(blog.vero.site)

18 points | by ibobev 1 day ago

1 comments

  • amelius 58 minutes ago
    > Many people know that you shouldn’t do decimal calculations, such as those involving U.S. dollars and cents, with the floating-point numbers in most programming languages. This is because decimal numbers can’t be expressed exactly as such floating-point numbers, so you will encounter rounding errors.

    Why not, rounding to the nearest cent is going to be much less precise for any realistic amount of dollars when using 64 bit floats (the type of float Javascript uses in every browser).

    • glimshe 11 minutes ago
      The rounding behavior with true decimals is easy to control and understand across number magnitudes and doesn't suffer from platform specific quirks like floats/doubles.

      The article's images clearly show the rounding error mess your get without decimals.

      • amelius 6 minutes ago
        But the rounding errors are way down in the nano-cents. Not worrying about them is cheaper!
        • glimshe 2 minutes ago
          If you're calculating your monthly expenses that's okay, but across millions of transactions of arbitrary amounts, something financial systems do regularly, aggregates start not adding up and you don't know where the money went.
    • knorker 3 minutes ago
      "The nearest cent" is already a bad assumption. Should IEEE 754 representation dictate taxes and money splitting?

      You could end up with splitting an account down the middle, and ending up with an extra cent being created out of thin air, or one destroyed. In billions of transactions each day, this could be a problem for balancing books when there is no longer any equality check.

      When not using floats, the rules and checks become more… deterministic, if you don't mind stretching the definition of that word a bit.