aspose file tools*
The moose likes Java in General and the fly likes storing money as a double Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "storing money as a double" Watch "storing money as a double" New topic
Author

storing money as a double

Y Cheong
Greenhorn

Joined: Jan 19, 2003
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

Joined: Jul 31, 2003
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.


Tom Blough<br /> <blockquote><font size="1" face="Verdana, Arial">quote:</font><hr>Cum catapultae proscriptae erunt tum soli proscripti catapultas habebunt.<hr></blockquote>
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: storing money as a double