How I saved my company one penny

Somedays as a developer you really know that your work affects the bottom line, and other days you are putting lipstick on a pig. This is my story of how I once saved my company a whole penny through a day of in the trenches code sleuthing. Money machine or hog hairdresser? You decide.

There were two components to our Java-based online commerce system: One to authorize funds from a credit card and another to draw the funds. The first used float values for money and the second used the Java BigDecimal class. The second operation failed once or twice a month because the charge didn't match the authorized amount. How could this be?

The Java code I inherited committed the cardinal sin of using a float to represent a monetary transaction. Joshua Bloch, in Effective Java devotes a full section to warning programmers why "float and double types are particularly ill-suited for monetary calculations." Consider the following example:

System.out.println(1.03 - .42);

The result is 0.6100000000000001. Not exactly what you want. Before you think that rounding will fix it, consider the compound effect of dozens of items, tax, shipping and discount multipliers. No matter how you cut it, a floating variable is imprecise.

After a day of refactoring our application to use BigDecimal values on both operations, everything went well and I proudly exclaimed to our team that I saved us a penny, but the larger implication was that orders weren't delayed and we could more effectively unit test the system from start to end.