Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 492
ControlAltDel Avatar asked Dec 20 '22 19:12

ControlAltDel


2 Answers

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.

like image 174
assylias Avatar answered Jan 07 '23 07:01

assylias


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

 equals( new BigDecimal("0.1") );
like image 32
Sirko Avatar answered Jan 07 '23 07:01

Sirko