Home
SOA
Spring-Hibernate
GOF Design Patterns
Java BP
Java Tutorial
Java Traps
Datawarehouse
C++ Tutorial
Unix Commands
Interview QnA
About MDC

Money matters in financial calculations:

 In a world where every one wants to save every penny to stay ahead of competition, a java application can’t afford to go wrong with business calculations. Whether it’s the interest calculation or mortgage calculation or tax lot and portfolio management, it needs to be accurate to the level of each penny. Using java sometime poses threat to such accuracy because of negligence or ignorance. Here are some ground rules for writing those pieces of software where money matters:

*      Sooner or later, everyone trying to calculate money in Java discovers that computers can't add, multiply and divide properly. Multiplication of 1219.00 with 5.56 as double/float results 6777.639999999999, not 6777.64. Similarly 8250325.12 and 4321456.31 adds up to 12571782.00, not 12571781.43. The details of the problem could be found in the IEEE 754 specification that defines how floating-point works.

*      We should use BigDecimal for most of money calculations where performance is not a big concern. BigDecimal is far more accurate than double or float but it is bulky. It also provides more flexible rounding options of currency. While formatting currency and percentages, keep in mind the target locale. For example: decimal is used as ‘,’ instead of ‘.’ In German locale.

*      If double is the only option then split the integral and decimal parts and then do addition. Writing such utility library to use across the application is a better idea.

*      For scientific application please go through the book Java Number Cruncher by Ronald Mak.  There are commercial libraries available in the market for financial applications. For example, Time Value of Money – Java Bean from GetObjects and PSPDEC from Prospero software. If time permits always try to write your own set of reusable components instead of using a third-party library.

*      Keep customer aware of all the possible issues in precision and get their count on it. Publish the blue print of all such calculations, which could be used by new developers in maintenance mode.

*      If the calculation is intensive and time consuming then use in-memory DB, Hibernate instead of conventional database.

*      Try to separate business rules from actual calculation. A simple XML schema or a complex rules engine could be used.