Java Tip: Resolving BigDecimal ArithmeticException

Financial Applications need precise and accurate calculations and this is achieved in Java using the java.math.BigDecimal class. While working with this class and using the divide(BigDecimal divisor) method I came across an issue which I wanted to describe here:

java.lang.ArithmeticException: Non-terminating decimal expansion; no exact representable decimal result

As per the Javadoc for BigDecimal this occurs since the ‘exact quotient cannot be represented’. This can be resolved by providing the scale (precision) and the RoundingMode ┬áto the divide() method. Something like this:

bdVar1.divide( bdVar2,6,RoundingMode.HALF_UP);

Where bdVar1 and bdVar2 are BigDecimals and 6 is the scale.

Hope this helps.

3 comments for “Java Tip: Resolving BigDecimal ArithmeticException

  1. Pingback:

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.