• 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

BigDecimal compareTo() problem

 
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I have 3 BigDecimal variables: a, b and c. I then do the following test:
if( a.add(b).compareTo(c) == 0 )

a = 49.9900000000000001827363995
b = 50.01
c = 100

This sum does not equal zero. How do I set the scale/rounding for all three BigDecimals to get the desired result to equal zero? These are dollar and cents amounts.
Thanks,
Joe
 
Ranch Hand
Posts: 323
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
is there any particular reason you have to use BigDecimal in particular to work with these dollar-and-cent amounts? couldn't you just use integers and BigIntegers to work with whole numbers of cents instead? then you wouldn't need to round anything at all.
 
Ranch Hand
Posts: 89
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Firstly the way I'm running your code actually works fine and returns true


However if you want it to make it bullet-proof you could try the following



Hope this helps,
Barry
 
Joe Busch
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks. I should be calling setScale(2, BigDecimal.ROUND_HALF_UP) on each BigDecimal I use, then the compares work properly.

I guess I could have also used a long and moved the dollar amounts, including pennies, into them. However I would then need to convert double to long as well as strings. Since I have only a small number of computations, BigDecimal was the quickest approach.

Thanks again for your solution.
 
reply
    Bookmark Topic Watch Topic
  • New Topic