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?
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.
You could use the string constructor of BigDecimal
(docu):
equals( new BigDecimal("0.1") );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With