Fundamentals 14 min read

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

This article provides an in‑depth introduction to Java's BigDecimal class, covering its purpose for high‑precision arithmetic, frequently used constructors, essential arithmetic and conversion methods, comparison techniques, number‑formatting examples, common exceptions during division, and a utility class that encapsulates typical operations.

Architecture Digest
Architecture Digest
Architecture Digest
Comprehensive Guide to Java BigDecimal: Overview, Constructors, Common Methods, Formatting, and Pitfalls

1. BigDecimal Overview

The java.math.BigDecimal class offers arbitrary‑precision arithmetic for numbers exceeding the 16‑digit limit of double . While float and double are suitable for approximate calculations, BigDecimal should be used when exact results are required.

2. Common Constructors

BigDecimal(int) – creates an instance from an int .

BigDecimal(long) – creates an instance from a long .

BigDecimal(double) – creates an instance from a double (may introduce precision loss).

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

2.1 Usage Example

BigDecimal a = new BigDecimal(0.1); // uses double constructor, loses precision
System.out.println("a values is:" + a);

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

Output:

a values is:0.1000000000000000055511151231257827021181583404541015625
=====================
b values is:0.1

Reason: The double constructor cannot represent 0.1 exactly, while the String constructor does.

3. Common Methods

add(BigDecimal) – addition.

subtract(BigDecimal) – subtraction.

multiply(BigDecimal) – multiplication.

divide(BigDecimal) – division (may throw ArithmeticException if non‑terminating).

toString() – converts to a string.

doubleValue() , floatValue() , longValue() , intValue() – conversion to primitive types.

3.1 Comparison

Use compareTo to compare two BigDecimal objects:

int result = bigDecimal1.compareTo(bigDecimal2);
// result < 0  → first is smaller
// result == 0 → equal
// result > 0  → first is larger

4. Formatting

BigDecimal can be formatted using NumberFormat for currency or percentages:

NumberFormat currency = NumberFormat.getCurrencyInstance();
NumberFormat percent = NumberFormat.getPercentInstance();
percent.setMaximumFractionDigits(3);

BigDecimal loan = new BigDecimal("15000.48");
BigDecimal rate = new BigDecimal("0.008");
BigDecimal interest = loan.multiply(rate);

System.out.println("贷款金额:" + currency.format(loan));
System.out.println("利率:" + percent.format(rate));
System.out.println("利息:" + currency.format(interest));

Result: 贷款金额: ¥15,000.48 利率: 0.8% 利息: ¥120.00

5. Common Exceptions

Division without a terminating decimal throws java.lang.ArithmeticException: Non‑terminating decimal expansion . Resolve by specifying a scale:

BigDecimal result = a.divide(b, 2, BigDecimal.ROUND_HALF_UP);

6. Summary

Use BigDecimal only when exact decimal computation is necessary; it is slower than primitive types. Prefer the String constructor, remember that each arithmetic operation creates a new immutable object, and handle division with an explicit scale.

6.1 Utility Class Example

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) {
        return new BigDecimal(v1).add(new BigDecimal(v2));
    }

    public static String add(String v1, String v2, int scale) {
        if (scale < 0) throw new IllegalArgumentException("The scale must be a positive integer or zero");
        return new BigDecimal(v1).add(new BigDecimal(v2)).setScale(scale, BigDecimal.ROUND_HALF_UP).toString();
    }

    // Similar methods for sub, mul, div, round, remainder, compare, etc.
}
JavaPrecisionArithmeticBigDecimalUtilityNumber Formatting
Architecture Digest
Written by

Architecture Digest

Focusing on Java backend development, covering application architecture from top-tier internet companies (high availability, high performance, high stability), big data, machine learning, Java architecture, and other popular fields.

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.