ControlAltDel
ControlAltDel

Reputation: 35096

Testing with percentages and BigDecimal

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

Answers (2)

assylias
assylias

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

Sirko
Sirko

Reputation: 74076

You could use the string constructor of BigDecimal (docu):

 equals( new BigDecimal("0.1") );

Upvotes: 4

Related Questions