This week's book giveaways are in the Refactoring and Agile forums.We're giving away four copies each of Re-engineering Legacy Software and Docker in Action and have the authors on-line!See this thread and this one for details.
Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!

# storing money as a double

Y Cheong
Greenhorn
Posts: 9
Hi
I have been looking around for how to do calculations on monetary amounts and found that BigDecimal is the class to use. Will this be of use if I store the end result as a double?
ie I pass in to monetary amounts 2.30 and 4.50 (GBP), convert these into BigDecimal to do the calculation, round the result to 2dp and store the result as a double. Is this of any additional benefit of doing normal double1 + double2, if I don't store the end result as a BigDecimal?
This is pretty urgent, so I hope someone can help
Y

Tom Blough
Ranch Hand
Posts: 263
The problem with representing decimal numbers is that conversion to binary causes repeating fractions. Much like 1/3 is 0.333333 in base 10, 0.10 base 10 is a repeating decimal in base 2.
When you do math (+-*/) on these repeating decimals, you can loose precision on the result. Using BigDecimal is one way to reduce this precision loss because BigDecimal can have more decimal places in the operands thus carrying the repeating decimal to a more accurate representation.
Another solution for currency is to convert the fractional amounts to integer values before performing math and then convert back afterwards. For example \$3.10 + \$4.30 = 310 + 430 = 740 = \$7.40.
The conversion is performed by multiplying the values by 100.0 and then casting to int's. Perform the math, then divide by 100.0 and store the result back into a double. This will reduce the round-off errors introduced by performing mahtematical operations on repeating decimals.
Hope this helps.