Home > Java > javaTutorial > How to Avoid 'ArithmeticException: Non-terminating decimal expansion' in BigDecimal Division?

How to Avoid 'ArithmeticException: Non-terminating decimal expansion' in BigDecimal Division?

Patricia Arquette
Release: 2024-11-12 10:50:02
Original
706 people have browsed it

How to Avoid

Avoiding Non-Terminating Decimal Expansions in BigDecimal Division

Java's BigDecimal class is designed to facilitate high-precision mathematical operations, but it can sometimes throw an "ArithmeticException: Non-terminating decimal expansion; no exact representable decimal result" error. This exception occurs when dividing two BigDecimal objects and the quotient has an infinite decimal expansion.

Reason for the Exception

According to the BigDecimal documentation, when no MathContext object (specifying precision and rounding mode) is provided, arithmetic operations are performed exactly. If the quotient has a non-terminating decimal expansion and cannot be represented exactly, the exception is thrown.

Example

BigDecimal a = new BigDecimal("1.6");
BigDecimal b = new BigDecimal("9.2");
a.divide(b) // raises the ArithmeticException
Copy after login

Fix

To resolve the issue, you can specify a MathContext object with a non-zero precision and a rounding mode. For example:

a.divide(b, 2, RoundingMode.HALF_UP)
Copy after login

Here, 2 specifies the scale (number of decimal places) and RoundingMode.HALF_UP denotes the rounding method.

Additional Information

  • ArithmeticContext objects allow you to control the rounding and precision of calculations.
  • If an exact result cannot be obtained, the operation will use the specified rounding mode to approximate the result.
  • Refer to the Java documentation or this blog post for more details: https://blog.frankel.ch/2013/09/avoid-arithmetic-exception-in-java-bigdecimals.html

The above is the detailed content of How to Avoid 'ArithmeticException: Non-terminating decimal expansion' in BigDecimal Division?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template