02/01/2009

Use BigDecimals for Financial Calculations: One More Example

Recently I was asked about the preferred data type in java application dealing with financial data. I suggest using of BigDecimal and here is the example why. Let's perform following arithmetic operations over double values, double values with strictfp mode enabled and over BigDecimals.

Expression is: "0.999/9 - 0.112"
Expected result is: "-0.001"

Java code:
import java.math.BigDecimal;

public class FloationPointTest {

public strictfp static void testStrictfp() {
System.out.println("strictfp: 0.999/9-0.112 = " + (0.999/9-0.112));
}

public static void main(String ... args) {
System.out.println("double: 0.999/9-0.112 = " + (0.999/9-0.112));
testStrictfp();
System.out.println("BigDecimal: 0.999/9-0.112 = " + (new BigDecimal("0.999").divide(new BigDecimal("9")).subtract(new BigDecimal("0.112"))));
}
}

Program output:
double: 0.999/9-0.112 = -0.0010000000000000009
strictfp: 0.999/9-0.112 = -0.0010000000000000009
BigDecimal: 0.999/9-0.112 = -0.001

We see that only operations with BigDecimal does not lead to the lost of precision. Performing operation over values of type double even in strictfp mode may loose accuracy. It is not acceptable for financial calculations in the days of Global financial crisis.

No comments:

Post a Comment

redirect