Comprehensive Guide to Java BigDecimal: Overview, Constructors, Methods, Formatting, and Common Pitfalls
This article explains Java's BigDecimal class, covering its purpose for high‑precision arithmetic, recommended constructors, key arithmetic methods, comparison techniques, formatting with NumberFormat, handling of division exceptions, and best‑practice tips such as using the String constructor and managing immutability.
BigDecimal Overview
Java's java.math.BigDecimal class provides arbitrary‑precision arithmetic for numbers beyond the 16‑digit limit of double , avoiding the precision loss of Double.valueOf(String) and Float.valueOf(String) .
Common Constructors
BigDecimal(int) , BigDecimal(double) , BigDecimal(long) , BigDecimal(String) – each creates an object from the corresponding type; the String constructor is recommended for exact values.
Usage Example
BigDecimal a = new BigDecimal(0.1);
System.out.println("a values is:" + a);
BigDecimal b = new BigDecimal("0.1");
System.out.println("b values is:" + b);The output shows the double constructor yields a long binary representation, while the String constructor produces the expected 0.1 .
Key Methods
add, subtract, multiply, divide, toString, doubleValue, floatValue, longValue, intValue, compareTo, and other utility methods for conversion and rounding.
Comparison
int cmp = bigDecimal1.compareTo(bigDecimal2);The result -1 , 0 , or 1 indicates less than, equal, or greater than respectively.
Formatting
NumberFormat can format BigDecimal values for currency and percent, e.g., using NumberFormat.getCurrencyInstance() and NumberFormat.getPercentInstance() .
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));Common Exceptions
The divide method may throw java.lang.ArithmeticException when the result is a non‑terminating decimal; specify a scale (e.g., divide(x, 2) ) to avoid this.
Summary
Use BigDecimal for precise calculations, prefer the String constructor, remember that BigDecimal objects are immutable, and handle scaling and rounding explicitly.
Architect's Guide
Dedicated to sharing programmer-architect skills—Java backend, system, microservice, and distributed architectures—to help you become a senior architect.
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.