BigDecimal and rounding
What you will learn
Use BigDecimal when an amount must follow decimal arithmetic and an explicit rounding policy. Unlike binary floating-point, decimal input such as 0.10 can be represented exactly. BigInteger handles integers beyond the range of long. Neither type removes the need to choose sensible bounds and validate input.
- Construct exact decimal values and calculate an invoice with an explicit scale and rounding policy.
- Distinguish BigDecimal numerical comparison from equals and hash-based equality.
- Choose BigInteger or checked primitive arithmetic when integer overflow matters.
Each example is a complete Main.java file. Use a fresh directory, javac --release 21 Main.java, then java Main. No external dependencies.
Calculate a fictional invoice
import java.math.*;import java.time.*;import java.time.format.*;import java.time.temporal.*;import java.text.*;import java.util.*;public class Main { public static void main(String[] args) throws Exception { BigDecimal price = new BigDecimal("19.95"); BigDecimal subtotal = price.multiply(BigDecimal.valueOf(3)); BigDecimal tax = subtotal.multiply(new BigDecimal("0.10")).setScale(2, RoundingMode.HALF_UP); System.out.println(subtotal.toPlainString()); System.out.println(tax.toPlainString()); System.out.println(subtotal.add(tax).toPlainString()); }}Expected output:
59.855.9965.84The policy rounds tax once to cents before adding it. The exact tax was 5.985, so the tie rounds upward.
Decimal scale, precision and construction
A BigDecimal represents an unscaled integer multiplied by ten to the negative scale. Scale is not precision: 12.30 has scale 2 and precision 4. A negative scale is possible, for example after stripping trailing zeros. Construct from a decimal string or a known integer. new BigDecimal(0.1) captures the actual binary double approximation, not the intended decimal 0.1. BigDecimal.valueOf(double) uses the double’s canonical string representation, but cannot undo arithmetic errors already introduced in double calculations. BigDecimal and BigInteger are immutable: save returned values.
Rounding is a domain decision
Use setScale(2, RoundingMode.HALF_UP) for this fictional invoice policy, not as a universal currency rule. HALF_UP rounds a tie away from zero; HALF_EVEN rounds ties to the even neighboring digit. DOWN truncates toward zero, FLOOR toward negative infinity. MathContext limits significant digits, not digits after the decimal point. Exact divide throws if a quotient does not terminate in base ten; choose a scale and rounding mode for an intentionally rounded quotient. Specify whether to round each line or the invoice total; these policies can differ. Carry currency identity separately and do not assume two decimal places for all currencies.
Equality and bounded arithmetic
compareTo treats 2.0 and 2.00 as numerically equal, while equals also compares scale. Their hash codes need not match. Choose a canonical representation for money keys, such as a validated fixed-scale value, instead of mixing equality policies. Math.addExact detects primitive overflow; BigInteger is useful when the required integer range exceeds long. Arbitrary precision still consumes memory and CPU, so bound input digits and exponents. Math and StrictMath provide floating-point mathematical functions; StrictMath specifies reproducible results for particular functions, not exact decimal arithmetic. Use tolerance for approximate results, not equality to every mathematically ideal result.
Compare scale and numeric value
import java.math.*;import java.time.*;import java.time.format.*;import java.time.temporal.*;import java.text.*;import java.util.*;public class Main { public static void main(String[] args) throws Exception { BigDecimal a = new BigDecimal("2.0"), b = new BigDecimal("2.00"); System.out.println(a.scale() + ":" + b.scale()); System.out.println(a.equals(b)); System.out.println(a.compareTo(b)); System.out.println(a.setScale(2).equals(b)); System.out.println(new BigDecimal(0.1).compareTo(new BigDecimal("0.1")) > 0); System.out.println(BigDecimal.valueOf(0.1).equals(new BigDecimal("0.1"))); }}Expected output:
1:2false0truetruetrueNumeric order ignores the representation scale. The double constructor exposes the approximation; valueOf uses the decimal string of that double.
Compare rounding and division
import java.math.*;import java.time.*;import java.time.format.*;import java.time.temporal.*;import java.text.*;import java.util.*;public class Main { public static void main(String[] args) throws Exception { BigDecimal tie = new BigDecimal("2.345"); System.out.println(tie.setScale(2, RoundingMode.HALF_UP)); System.out.println(tie.setScale(2, RoundingMode.HALF_EVEN)); System.out.println(BigDecimal.ONE.divide(BigDecimal.valueOf(3), 4, RoundingMode.HALF_UP)); System.out.println(new BigDecimal("123.45").round(new MathContext(3, RoundingMode.HALF_UP))); }}Expected output:
2.352.340.3333123Scale and significant-digit precision answer different questions. One third requires a rounding policy.
Large integers and checked overflow
import java.math.*;import java.time.*;import java.time.format.*;import java.time.temporal.*;import java.text.*;import java.util.*;public class Main { public static void main(String[] args) throws Exception { BigInteger huge = BigInteger.valueOf(Long.MAX_VALUE).add(BigInteger.ONE); System.out.println(huge); try { Math.addExact(Long.MAX_VALUE, 1L); } catch (ArithmeticException ex) { System.out.println("overflow"); } System.out.println(StrictMath.sqrt(81)); System.out.println(Math.abs(Math.sin(Math.PI)) < 1e-12); }}Expected output:
9223372036854775808overflow9.0trueBigInteger extends the usable integer range; checked arithmetic detects overflow rather than wrapping. The sine check uses a tolerance.
Common mistakes
Avoid using double for exact currency calculations, silently rounding at each step, or comparing decimal values with ==. Do not ignore a returned immutable value. An exact quotient may be impossible even when both operands are exact decimals. Reject malformed or excessively large inputs at the boundary.
Practice
Three items cost 3.35 each. Apply a 7.5% fictional tax to the subtotal, round tax to two decimals using HALF_EVEN, and print subtotal, tax and total.
Expected output:
10.050.7510.80Compare your answer with the manual practice criteria.
Official reading: BigDecimal · BigInteger. Java 25 execution remains unverified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
BigDecimal and rounding — knowledge check
Original arithmetic, time and localization questions. Java 21-compatible scope.
Which constructs exact decimal 0.1?
What is 2.0.compareTo(2.00) for BigDecimal values?
What does exact divide do for 1 / 3?
What does MathContext precision count?
How can long overflow be detected during addition?