Computers Can’t Add

That’s right.. computer can’t add gud. Here is a small example:

        BigDecimal money1 = new BigDecimal(.1);
        BigDecimal money2 = new BigDecimal(.2);
        BigDecimal total = money1.add(money2);
        
        double moneyDouble1 = .1;
        double moneyDouble2 = .2;
        double totalDouble = moneyDouble1+moneyDouble2;

        NumberFormat formatter = NumberFormat.getCurrencyInstance();
        String moneyStringBigDecimal = formatter.format(total);
        System.out.println("BigDecimal       =  " + total);
        System.out.println("double           =  " + totalDouble); 
        System.out.println("Formatted money  = " + moneyStringBigDecimal);  

You would expect the output to be:

Formatted money  = $0.30
BigDecimal =  0.30
double = 0.30

But the output is actually this!

Formatted money  = $0.30
BigDecimal       =  0.3000000000000000166533453693773481063544750213623046875
double           =  0.30000000000000004

So, why is this? The reason for this is that floating point hardware architectures are trying to approximate a floating point number down to the infinite place and are limited by the zeros and ones our computers use for calculations.

In order to understand this in more detail, we have to dig into how computers, specifically how floating-point arithmetic modules are built. Since this is a more complicated subject, it may be a future article. But for now, there are many great youtube videos like this or this to help you understand more of the details. If you are feeling like having a super good time, you could read through the standard floating point architecture documentation, known as IEEE 754.

As a software developer, you could go through life never digging into this topic. Modern software libraries, like BigDecimal have abstracted much of this pain away.

If however, you are working on critical applications that require exacting calculations in critical places like, landing on the moon, your team should define their standards, document them, and code review to make sure they are met.

Previous
Previous

Hiring: Know Your Employee Types

Next
Next

Be Like Water - Learn Fast Daily