Search code examples
javaprecisionbigdecimaltrailing

BigDecimal Precision Issue?


I am writing a program in which I have to repeatedly multiply two BigDecimal.

After the 27th iteration, I get:

0.905225895893387921845435055445776361046057346344145563957027726

Any further calculations using this number (BigDecimal * 0.182365681285) results in trailing zeros. So the next iteration returns: 0.905225895893387921845435055445776361046057346344145563957027726000000000000

The iteration after that returns: 0.905225895893387921845435055445776361046057346344145563957027726000000000000000000000000

etc..


So I was wondering if this was due to some precision issue with BigDecimal.

Any help is appreciated

Edit: I was asked to post my code. I could copy paste the few pages I have, but this is a very accurate representation of what I have so far:

BigDecimal range = new BigDecimal(0.0012440624293146346);
for(int i = 0; i < 50 ; i++){
    low = low.multiply(range);
}

Solution

  • The multiply method creates a BigDecimal which has a scale equal to the scale of the first operand + the scale of the second operand, even if that leads to trailing zeros. To strip the trailing zeros, use... stripTrailingZeros().