‹ 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. sluukkonen · · focus · HN ↗
      It’s easier just to use a proper decimal type than to remember all of the ways where using floats will bite you in the ass. The behavior is unintuitive even in trivial examples. Code like

        amount_due = 0.10 + 0.20
        amount_paid = 0.30
        
        if amount_paid >= amount_due:
            print("PAID")
        else:
            print("OUTSTANDING")
      
      will print “OUTSTANDING”.
      1. AlotOfReading · · focus · HN ↗
        Decimals can bite you in the ass too. Try dividing by 3, or using transcendental functions.

        Changing representations isn't a substitute for the numerical analysis you should be doing for financial calcs.

Open on Hacker News to reply ↗

Unofficial Hacker News client; not affiliated with Y Combinator.