Comprehensive Guide to Java BigDecimal: Constructors, Methods, Formatting, and Common Pitfalls
This article explains Java's BigDecimal class, covering its purpose for high‑precision arithmetic, common constructors, essential methods such as add, subtract, multiply, divide, formatting techniques, handling of non‑terminating decimals, and provides a utility class with examples and best‑practice recommendations for developers.
Java provides the BigDecimal class in the java.math package for precise calculations beyond the 16‑digit limit of double. While float and double are suitable for many cases, they lose precision when converting from String or when representing numbers like 0.1.
BigDecimal Common Constructors
1. Common Constructors
BigDecimal(int) – creates an instance from an int value.
BigDecimal(double) – creates an instance from a double value (may introduce precision issues).
BigDecimal(long) – creates an instance from a long value.
BigDecimal(String) – creates an instance from a String representation (recommended for exact values).
2. Usage Issue Analysis
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.1Analysis:
The double constructor may produce an unexpected value because 0.1 cannot be represented exactly in binary floating‑point.
The String constructor yields the exact expected value, so it is generally preferred.
If a double must be used, prefer BigDecimal.valueOf(double) which internally uses Double.toString(double) to avoid the precision problem.
BigDecimal Common Methods Detail
1. Common Methods
add(BigDecimal) – returns the sum.
subtract(BigDecimal) – returns the difference.
multiply(BigDecimal) – returns the product.
divide(BigDecimal) – returns the quotient (may throw ArithmeticException if the division is non‑terminating).
toString() – converts the value to a String.
doubleValue() , floatValue() , longValue() , intValue() – convert to primitive types.
2. BigDecimal Comparison
Use compareTo to compare two BigDecimal objects:
int a = bigDecimal1.compareTo(bigDecimal2);
// a = -1 (less), 0 (equal), 1 (greater)BigDecimal Formatting
With NumberFormat you can format monetary or percentage values using a BigDecimal as the source:
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: 贷款金额: ¥15,000.48 利率: 0.8% 利息: ¥120.00 Formatting with two decimal places and zero‑padding can be done via DecimalFormat:
public static String formatToNumber(BigDecimal obj) {
DecimalFormat df = new DecimalFormat("#.00");
if (obj.compareTo(BigDecimal.ZERO) == 0) {
return "0.00";
} else if (obj.compareTo(BigDecimal.ZERO) > 0 && obj.compareTo(new BigDecimal(1)) < 0) {
return "0" + df.format(obj);
} else {
return df.format(obj);
}
}Common Exceptions
Division Exception
java.lang.ArithmeticException: Non-terminating decimal expansion; no exact representable decimal resultWhen dividing with divide and the result is a repeating decimal, specify a scale and rounding mode, e.g., divide(divisor, 2, RoundingMode.HALF_UP).
Summary
1. Key Takeaways
Use BigDecimal only when exact decimal precision is required; it is slower than double. Prefer the String constructor for predictable results. Remember that BigDecimal is immutable, so each arithmetic operation returns a new instance.
2. 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();
}
// ... other overloaded add, sub, mul, div, round, remainder, compare methods ...
}The article ends with a reminder that the content is for Java architects and includes promotional links to additional resources.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Java Architect Essentials
Committed to sharing quality articles and tutorials to help Java programmers progress from junior to mid-level to senior architect. We curate high-quality learning resources, interview questions, videos, and projects from across the internet to help you systematically improve your Java architecture skills. Follow and reply '1024' to get Java programming resources. Learn together, grow together.
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.
