Reputation: 35096
I have two BigDecimals Actual, and Budgeted. I am dividing Actual by Budgeted to come up with a percent.
The problem I'm having is that as I am building some unit tests, I am trying to confirm that the resulting BigDecimal is .1 but when try equals(new BigDecimal(.1)) this fails because of double accuracy issues.
The way I was thinking of overcoming this was to create two BigDecimals - ten and hundred, divide those two and use that to test with. This way, I'm only using fixed point numbers and my calculations should work out exactly.
So my question is: is there a better way to do this?
Upvotes: 4
Views: 2313
Reputation: 328735
When using BigDecimal, you should make "number equality" tests using the compareTo
method instead of the equals
method:
if (bigDecimal1.compareTo(bigDecimal2) == 0) { //then they are equals
cf. javadoc for more information.
And as others have mentioned, you should use the string constructor to avoid rounding issues.
Upvotes: 7