BigDecimals are a combination of a number and a 'scale'. 2 BDs dont consider themselves equal unless both are equal. I suggest using .compareTo(other) == 0)
to get the answer.
NB: I don't think using BD is a good way to do currency.
There are generally 2 ways to approach currency. The easy way and the hard way.
The easy way is to store cents in an int
or long
. So, store $0.40 as simply 40
, and something like $12.50 would be stored as 1250
. You now have 2 problems: You can't represent half-cents, and overflow can happen (you can't represent an amount higher than 2^31-1 cents, but that's.. a lot of cents. Make it a long
and we're well beyond the GDP of the entire world).
But, half-cents are a problem in general. Take this issue:
I have 4 cents. I wish to divide these amongst 3 people.
So, what do we do? BigDecimal can't help you out here; you can't represent 4 divided by 3 with BD with perfection. YOu have to round SOMEWHERE (it's 1.33333333... BD can't represent infinite sequences). Even if it could or you decide to round at some egregious amount (lets say 200 digits), now what? You can't tell your bank to transfer a third of a cent. There are no easy answers: If this is what your app needs to do, then you need to decide how to deal with this. For example, 'the remaining cent is for the house' or 'the software picks a random recipient; they get 2 cents, the other 2 get a single cent).
In other words, if 'just use an int/long' doesn't do it, odds are BigDecimal is no good either.