• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

storing money as a double

 
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
 
Ranch Hand
Posts: 263
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic