I would also recommend using nothing but BigDecimal for ALL arithmetic operations, which may include currency.
Make sure you always use the String BigDecimal constructor. What for? Try the following code in the JUnit test:
assertEquals(new BigDecimal("0.01").toString(), new BigDecimal(0.01).toString());
You get the following result:
expected:<0.01[]> but was <0.01[000000000000000020816681711721685132943093776702880859375]>
In truth, you cannot store EXACTLY 0.01 as a “double” amount. Only BigDecimal saves the number you need EXACTLY how you want it.
And remember that BigDecimal is immutable. The following will compile:
BigDecimal amount = new BigDecimal("123.45"); BigDecimal more = new BigDecimal("12.34"); amount.add(more); System.out.println("Amount is now: " + amount);
but the resulting output will be:
Amount now: 123.45
This is because you need to assign the result to a new (or the same) BigDecimal variable.
In other words:
amount = amount.add(more)
DuncanKinnear Dec 13 '11 at 23:17 2011-12-13 23:17
source share