Comprehensive Guide to Java BigDecimal: Constructors, Methods, Formatting, and Common Exceptions
This article explains Java's BigDecimal class, covering its constructors, precise arithmetic operations, formatting techniques, common pitfalls with double values, comparison methods, exception handling, and provides a utility class with comprehensive methods for accurate calculations.
Java provides the java.math.BigDecimal class for high‑precision arithmetic beyond the 16‑digit limit of double , making it essential when exact decimal calculations are required.
Common Constructors
new BigDecimal(int) – creates an instance from an integer value.
new BigDecimal(double) – creates an instance from a double value (may introduce precision loss).
new BigDecimal(long) – creates an instance from a long value.
new BigDecimal(String) – creates an instance from a string representation, preserving the exact value.
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);Result:
a values is:0.1000000000000000055511151231257827021181583404541015625
=====================
b values is:0.1Reason Analysis
The BigDecimal(double) constructor inherits the binary representation error of the double literal (e.g., 0.1 cannot be represented exactly), leading to an unexpected long decimal expansion.
The BigDecimal(String) constructor is deterministic and should be preferred for exact values.
If a double must be used, invoke BigDecimal.valueOf(double) which internally uses Double.toString(double) to avoid the extra error.
Common Methods
add(BigDecimal) – addition.
subtract(BigDecimal) – subtraction.
multiply(BigDecimal) – multiplication.
divide(BigDecimal) – division (may throw ArithmeticException if non‑terminating).
toString() – converts to string.
doubleValue() , floatValue() , longValue() , intValue() – converts to primitive types.
Size Comparison
int result = bigDecimal1.compareTo(bigDecimal2);
// result = -1 if less, 0 if equal, 1 if greaterFormatting with NumberFormat
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));Output:
贷款金额: ¥15,000.48 利率: 0.8% 利息: ¥120.00Common Exception
java.lang.ArithmeticException: Non-terminating decimal expansion; no exact representable decimal resultThis occurs when divide is called on a non‑terminating decimal without specifying a scale. The fix is to use the overloaded divide(BigDecimal divisor, int scale) method or divide(BigDecimal divisor, int scale, RoundingMode) .
Summary
Use BigDecimal only when exact decimal precision is required; prefer the String constructor, remember that BigDecimal is immutable, and always store the result of arithmetic operations.
Utility Class Recommendation
package com.vivo.ars.util;
import java.math.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) {
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.
}Selected Java Interview Questions
A professional Java tech channel sharing common knowledge to help developers fill gaps. Follow us!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.