‹ BackHN Continuity

Thread

Adding Floating-Point Decimals for Fun and Profit

62 points · 35 comments · ibobev

  1. amelius · · focus · HN ↗
    > 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).

    1. glimshe · · focus · HN ↗
      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.

      1. amelius · · focus · HN ↗
        But the rounding errors are way down in the nano-cents. Not worrying about them is cheaper!
        1. glimshe · · focus · HN ↗
          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.
        2. andreareina · · focus · HN ↗
          The decimal library worries about rounding, that's basically free. With floats you need to decide when to use rounding (because you don't want to show a balance of -0.000000086) and it's more difficult to use automatic checks for the same reason.
Open on Hacker News to reply ↗

Unofficial Hacker News client; not affiliated with Y Combinator.