Last reviewed: 2026-11-21.

A Java money patch is ready for review only when its rounding policy is explicit and its tests distinguish that policy from plausible alternatives. Ask the coding agent where decimal values enter, where rounding occurs, and which mode applies; then check its answers against independently calculated examples. BigDecimal preserves decimal arithmetic, but it does not choose the currency scale, legal rule, or rounding point for you.

This walkthrough uses Java 21 and a deliberately narrow sample policy: decimal text inputs, amounts representable at two fractional places, a decimal tax rate, and HALF_EVEN rounding once per line to two places. That is an example contract, not a rule for every currency, tax system, or invoice. Some currencies use a different number of fractional places; confirm the actual business and jurisdictional requirements before adopting a policy.

Fix the money contract before reading the diff

Write down the decisions that a reviewer can test. If the ticket does not answer one, ask the domain owner before treating an agent’s choice as correct:

  • Inputs: Which currency and units do amounts represent? Is a value decimal text, an integer number of minor units, or a decimal from an API? What range, syntax, and rate precision are allowed?
  • Rounding: How many fractional places does this operation require, which rounding mode applies, and what happens to negative amounts and ties?
  • Timing: Is tax or a discount rounded on each line, for each tax category, or only after summing a base? Are separately rounded components added, and how are residuals allocated?
  • Boundaries: What is saved, displayed, and returned to callers? Must the application reject a value that needs rounding at input, or accept and round it? How should errors be reported?

Put these answers next to test vectors from a trusted specification or domain expert, including a credit or refund. An agent can locate every conversion and arithmetic call, but it should not infer financial policy from a convenient library default. The sample below deliberately fixes one policy so its expected values can be checked by hand.

Run a concrete rounding check

Save the following as InvoiceRoundingCheck.java. It uses only the Java standard library. amount accepts a value only if reducing it to two places requires no rounding; tax multiplies that normalized amount by the supplied rate, then rounds each line. The helper checks both value and scale so an expected 1.00 remains distinguishable from 1.0.

import java.math.BigDecimal;
import java.math.MathContext;
import java.math.RoundingMode;

public class InvoiceRoundingCheck {
    static BigDecimal amount(String text) {
        return new BigDecimal(text).setScale(2, RoundingMode.UNNECESSARY);
    }

    static BigDecimal tax(String net, String rate) {
        return amount(net).multiply(new BigDecimal(rate))
                .setScale(2, RoundingMode.HALF_EVEN);
    }

    static void check(String expected, BigDecimal actual) {
        if (!new BigDecimal(expected).equals(actual)) {
            throw new AssertionError("Expected " + expected + ", got " + actual);
        }
    }

    public static void main(String[] args) {
        check("1.00", tax("10.05", "0.10"));
        check("1.02", tax("10.15", "0.10"));
        check("-1.02", tax("-10.15", "0.10"));
        check("1.00", amount("1.000"));
        try {
            amount("1.001");
            throw new AssertionError("Expected excess precision to fail");
        } catch (ArithmeticException expected) { }

        check("0.00", tax("0.05", "0.10").add(tax("0.05", "0.10")));
        check("0.01", tax("0.10", "0.10"));
        BigDecimal a = new BigDecimal("2.0");
        BigDecimal b = new BigDecimal("2.00");
        if (a.compareTo(b) != 0 || a.equals(b)) {
            throw new AssertionError("Equality semantics changed");
        }
        check("0.33", new BigDecimal("1").divide(
                new BigDecimal("3"), 2, RoundingMode.HALF_EVEN));
        try {
            new BigDecimal("1").divide(new BigDecimal("3"));
            throw new AssertionError("Expected exact division to fail");
        } catch (ArithmeticException expected) { }
        BigDecimal x = new BigDecimal("123.45");
        if (x.round(new MathContext(2, RoundingMode.HALF_EVEN))
                .compareTo(new BigDecimal("120")) != 0) {
            throw new AssertionError("Unexpected precision rounding");
        }
        check("123.45", x.setScale(2, RoundingMode.HALF_EVEN));
        System.out.println("All checks passed");
    }
}

Compile and run it with a Java 21 JDK:

javac InvoiceRoundingCheck.java
java InvoiceRoundingCheck

The expected output is All checks passed. The checks throw an AssertionError on a mismatch; they do not depend on enabling Java’s assert flag. I ran the example with OpenJDK 21 and observed that output. As a local sensitivity check, I changed HALF_EVEN to HALF_UP in a copy: the first tie failed with Expected 1.00, got 1.01. This demonstrates that one test detects that particular policy change; it does not prove the production patch is correct.

The test rate is 0.10, meaning ten percent. For 10.05, the unrounded result is 1.005, which becomes 1.00 under the sample’s half-even rule. For 10.15, 1.015 becomes 1.02; -1.015 becomes -1.02. On an exact tie, half-even selects the neighbor whose retained digit is even, whereas half-up moves away from zero. The signed examples and definitions are documented in Oracle’s RoundingMode reference .

Trace decimal input and equality through the patch

Follow every value from its source to the first BigDecimal. For decimal text, new BigDecimal("10.05") preserves the intended decimal value. By contrast, new BigDecimal(10.05) captures the exact value of the already approximated binary double, which can contain many unexpected decimal digits. Oracle documents this distinction in the BigDecimal constructor reference . Converting after earlier floating-point arithmetic cannot restore decimal information that was already lost. If an upstream interface supplies a double, decide how to change or constrain that boundary rather than assuming a later conversion fixes the entire calculation.

The sample’s setScale(2, UNNECESSARY) is a useful exactness guard, not a syntax validator. It accepts "1.000" and returns 1.00, because removing a zero requires no rounding; it throws ArithmeticException for "1.001". It does not enforce a currency, allowed range, rate precision, or a rule that the original text contain at most two digits after the decimal point. Validate the accepted input grammar and bounds separately, and handle malformed text and the arithmetic exception at the application boundary. If the contract permits more precision and specifies rounding instead of rejection, encode that rule explicitly.

Scale also affects equality. new BigDecimal("2.0").compareTo(new BigDecimal("2.00")) returns zero, while equals returns false because the representations have different scales. Use compareTo when the business question is numerical equality. Use equals when representation and scale are part of the contract, as in the example’s output checks. For persisted values, keys, and serialized responses, decide whether to normalize scale consistently and test that decision; otherwise, two numerically equal values may behave differently in equality-based code.

Test the point of rounding and precision

The sample makes the aggregation decision visible. Two lines of 0.05 at a 0.10 rate each produce 0.005. Half-even rounding each line to two places gives 0.00 + 0.00 = 0.00. Combining the bases first gives 0.10 × 0.10 = 0.010, or 0.01 after rounding. Both calculations are internally consistent; only the agreed contract tells you which is right. Add a test that goes through the real invoice aggregation path, not just a helper that rounds one value, and verify the resulting line items and total. Include multiple tax rates or discounts if the production calculation supports them.

Inspect division separately. Exact new BigDecimal("1").divide(new BigDecimal("3")) throws ArithmeticException because the quotient has a non-terminating decimal expansion. If the business rule requires a rounded result, specify both the result scale and mode, as the example does to produce 0.33. Do not add a catch that silently substitutes zero. Define how callers receive invalid input or an unrepresentable result, and test that path as well as the normal result.

A MathContext precision is a count of significant digits, not the number of digits after the decimal point. For example, rounding 123.45 with precision two and HALF_EVEN gives a value numerically equal to 120; setting scale two leaves 123.45. This distinction follows the MathContext reference . Review each operation that receives a context: an intermediate multiplication or division may lose precision before a later setScale call. A final scale change cannot recover digits already discarded.

Turn the contract into a merge decision

Ask the agent for a list of input conversions, arithmetic operations, rounding calls, persistence points, and affected tests. Compare that map with the diff and search for other callers of the changed methods. For each path, record the exact input, unrounded intermediate, chosen rounding point, and expected output. Include positive and negative ties, values just below and above a tie, zero, permitted limits, invalid inputs, and a case where line rounding differs from total rounding. Derive expected results independently from the agreed rule; copying the implementation’s helper into the test oracle can make the same mistake appear on both sides.

Run the focused tests and the existing integration suite for the affected invoice or payment flow. Check that storage and API round trips preserve the agreed value and representation, and that a rejected amount does not leave a partial business operation. If a requirement is unresolved, mark that decision in the review and get an owner to settle it before merging. For broader input coverage, use property-based tests for agent patches after establishing a few trustworthy examples. A deliberate wrong-mode or wrong-rounding-point change can also show whether tests catch a meaningful regression; the guide to making agent-written tests catch bugs describes that review technique.

Sources checked

These versioned Java 21 references were checked on November 20, 2026 UTC. They are stable primary API documentation for the version used in the example; business rounding rules still require a separate authoritative policy for the application.