Backend Development 16 min read

Comprehensive Guide to Java BigDecimal: Overview, Constructors, Methods, Formatting, and Common Exceptions

This article explains Java's BigDecimal class for high‑precision arithmetic, covering its purpose, common constructors, usage examples, essential arithmetic and comparison methods, formatting techniques with NumberFormat, handling of division exceptions, and a summary of best practices with a utility class example.

Top Architect
Top Architect
Top Architect
Comprehensive Guide to Java BigDecimal: Overview, Constructors, Methods, Formatting, and Common Exceptions

1. BigDecimal Overview

Java provides the java.math.BigDecimal class for precise arithmetic on numbers with more than 16 significant digits. The double type can handle up to 16 digits but loses precision for larger or smaller numbers.

When exact precision is required, especially when converting from a string, use BigDecimal instead of Float or Double.

BigDecimal objects cannot be used with the usual arithmetic operators (+, -, *, /); you must call the corresponding methods, and the arguments must also be BigDecimal objects.

2. Common Constructors

2.1 Constructors

BigDecimal(int) – creates a BigDecimal from an int value.

BigDecimal(double) – creates a BigDecimal from a double value (may introduce unexpected precision).

BigDecimal(long) – creates a BigDecimal from a long value.

BigDecimal(String) – creates a BigDecimal from a string representation (recommended for exact values).

2.2 Usage Example

BigDecimal a = new BigDecimal(0.1);
System.out.println("a values is:" + a);
System.out.println("=====================");
BigDecimal b = new BigDecimal("0.1");
System.out.println("b values is:" + b);

The output shows that the double constructor yields a long decimal expansion, while the String constructor preserves the exact value 0.1.

Analysis explains why the double constructor is unpredictable and why the String constructor is preferred.

When a double must be used, use BigDecimal.valueOf(double) to obtain a predictable result.

3. Common Methods

3.1 Arithmetic Methods

add(BigDecimal) – addition.

subtract(BigDecimal) – subtraction.

multiply(BigDecimal) – multiplication.

divide(BigDecimal) – division.

toString() – converts the value to a string.

doubleValue() – converts to double.

floatValue() – converts to float.

longValue() – converts to long.

intValue() – converts to int.

3.2 Comparison

Use compareTo to compare two BigDecimal values; it returns -1, 0, or 1.

int a = bigDecimal.compareTo(bigDecimal2);

4. Formatting

NumberFormat can format BigDecimal values for currency, percentages, etc.

NumberFormat currency = NumberFormat.getCurrencyInstance();
NumberFormat percent = NumberFormat.getPercentInstance();
percent.setMaximumFractionDigits(3);
BigDecimal loanAmount = new BigDecimal("15000.48");
BigDecimal interestRate = new BigDecimal("0.008");
BigDecimal interest = loanAmount.multiply(interestRate);
System.out.println("贷款金额:\t" + currency.format(loanAmount));
System.out.println("利率:\t" + percent.format(interestRate));
System.out.println("利息:\t" + currency.format(interest));

Result: loan amount ¥15,000.48, rate 0.8%, interest ¥120.00.

A custom formatting method formatToNumber demonstrates handling of zero, values between 0 and 1, and values greater than 1.

5. Common Exceptions

5.1 Division Exception

Dividing with divide may throw java.lang.ArithmeticException: Non‑terminating decimal expansion; no exact representable decimal result when the result is a repeating decimal.

Solution: specify a scale, e.g., divide(x, 2) , to define the number of decimal places.

6. Summary

6.1 Key Points

Use BigDecimal for precise decimal calculations; it is slower than double/float and creates new objects for each operation.

Prefer the String constructor for exact values.

BigDecimal is immutable; each arithmetic operation returns a new instance, so store the result.

6.2 Utility Class Example

The following utility class provides static methods for precise addition, subtraction, multiplication, division, rounding, remainder, and comparison using BigDecimal.

public class ArithmeticUtils {
    private static final int DEF_DIV_SCALE = 10;
    public static double add(double v1, double v2) {
        BigDecimal b1 = new BigDecimal(Double.toString(v1));
        BigDecimal b2 = new BigDecimal(Double.toString(v2));
        return b1.add(b2).doubleValue();
    }
    public static BigDecimal add(String v1, String v2) {
        BigDecimal b1 = new BigDecimal(v1);
        BigDecimal b2 = new BigDecimal(v2);
        return b1.add(b2);
    }
    // Other methods (sub, mul, div, round, remainder, compare) omitted for brevity
}
JavaPrecisionArithmeticBigDecimalformatting
Top Architect
Written by

Top Architect

Top Architect focuses on sharing practical architecture knowledge, covering enterprise, system, website, large‑scale distributed, and high‑availability architectures, plus architecture adjustments using internet technologies. We welcome idea‑driven, sharing‑oriented architects to exchange and learn together.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.