I mentioned in one of my latest entries that I’ve done a bunch of fixed point stuff in Java lately. I work for a company that does many financial calculations, and much of the legacy code is in other languages. There’s always been a problem with rounding and consistency in these calculations. They’ve all been addressed, but there’s always pain to get it through testing when a change to calculation code arises.

Martin Fowler has discussed in several venues the idea of having a class that represents Money. This ensures semantic consistency, rounding precision, and especially it provides an allocate method to distribute Money among various individuals or accounts without losing any fractions. Everything is accounted for correctly.

We not only deal with Money, but other values which we must treat as always having exactly n number of decimals. Martin Fowler’s examples have often included code, and this guy wrote a Money class in the same spirit. But I didn’t want to rely on my own fixed point caculations to do the job right (you know, losing precision, increasing scale based on the arithmetic function performed, and all that stuff that’s real easy to ignore — even though you know it’s gonna come back and bite). I poked around and found out that IBM has done a great job of it already. They submitted a JSR long ago, and you can see that their work has been incorporated into J2SE 1.5 (or 5.0 — silly Sun marketing droids).

If you need to do reliable fixed point or decimal floating point calculations in Java, and you aren’t moving to J2SE 5.0 immediately, check out the small decimal.jar in this ZIP file (there’s even decimal1.jar for the 0.004% of Java users stuck on JDK 1.1) from IBM. It just may save the day.