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. December 9, 2010 at 1:13 pm

    this post is very usefull thx!

  2. June 26, 2014 at 2:47 am

    Spot on with this write-up, I actually believe this site needs a great deal more attention. I’ll probably be returning to see
    more, thanks for the information!

  3. 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.