Two lines of 0.335 can add up to either 0.68 or 0.67 in a report that shows two decimal places. Round each line before adding and the report shows 0.34 + 0.34 = 0.68. Add the exact amounts first and the total is 0.670, displayed as 0.67. Both outcomes use the same rounding mode. The difference is where it was applied.

This Java BigDecimal example turns that difference into a runnable fixture. It takes fictional decimal unit prices and integer quantities, multiplies each line exactly, and prints both totals. The goal is to make the rounding boundary explicit so the same inputs and rule produce the same result every time.

Use a JDK and decimal text

Install or select JDK 17 or newer and check that java and javac refer to it. The fixture has no external dependencies. Download the complete Java invoice rounding example, extract it, and open a terminal inside java-decimal-rounding. You can also save the source below as InvoiceDemo.java and run it separately.

Use a string such as "0.335" to represent the intended decimal. The BigDecimal API reference explains that constructing from a double retains the exact value of the binary approximation. Even when a printed double looks right, that approximation can sit on the other side of a rounding boundary. Converting the result of earlier floating-point arithmetic cannot reconstruct the original decimal inputs.

Complete InvoiceDemo.java

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;
import java.util.Objects;

public class InvoiceDemo {
    record Line(BigDecimal unitPrice, int quantity) {
        Line {
            Objects.requireNonNull(unitPrice, "unitPrice");
            if (unitPrice.signum() < 0 || unitPrice.scale() > 4) {
                throw new IllegalArgumentException("Use a nonnegative price with up to four decimal places");
            }
            if (quantity <= 0) {
                throw new IllegalArgumentException("Quantity must be positive");
            }
        }

        static Line of(String decimal, int quantity) {
            if (decimal == null || !decimal.matches("[0-9]{1,12}(\\.[0-9]{1,4})?")) {
                throw new IllegalArgumentException("Use a plain decimal such as 12.3400");
            }
            return new Line(new BigDecimal(decimal), quantity);
        }

        BigDecimal exactAmount() {
            return unitPrice.multiply(BigDecimal.valueOf(quantity));
        }
    }

    static BigDecimal total(List<Line> lines, boolean roundEachLine) {
        BigDecimal sum = BigDecimal.ZERO;
        for (Line line : lines) {
            BigDecimal amount = line.exactAmount();
            sum = sum.add(roundEachLine ? round(amount) : amount);
        }
        return round(sum);
    }

    private static BigDecimal round(BigDecimal amount) {
        return amount.setScale(2, RoundingMode.HALF_UP);
    }

    public static void main(String[] args) {
        List<Line> lines = List.of(Line.of("0.335", 1), Line.of("0.335", 1));
        System.out.println("Round each line: " + total(lines, true).toPlainString());
        System.out.println("Round the total: " + total(lines, false).toPlainString());
    }
}

Line.of checks a narrow input format before parsing. Its pattern accepts unsigned digits with an optional decimal point and one to four digits after it. It rejects separators, spaces, exponent notation and negative values. A line can have a zero price, but the quantity must be positive. These are choices for this fixture, not general BigDecimal restrictions.

First compute the extended line amount with multiply. Rounding the unit price first can change the outcome when the quantity is greater than one. At quantity two, one line at 0.335 has an exact extended amount of 0.670 and a rounded amount of 0.67. That is a different grouping from two lines that each have quantity one.

The total method either rounds each extended amount or adds it unchanged. The final setScale gives both results exactly two decimal places; for the sum of already rounded lines this does not discard more precision. The RoundingMode reference defines HALF_UP as rounding to the nearest value, with exact ties away from zero. Here it makes each positive 0.335 become 0.34.

Compile and compare the output

javac InvoiceDemo.java InvoiceTest.java
java InvoiceDemo
java InvoiceTest

If you copied only the source shown above, compile with javac InvoiceDemo.java and omit the test command. The ZIP contains both source files. Expected demo output:

Round each line: 0.68
Round the total: 0.67

On 8 November 2026 the source and separately extracted ZIP both compiled on Microsoft OpenJDK 17.0.11 for Windows with javac -Xlint:all. Both runs matched the expected demo output and passed all 12 checks. They cover both rounding boundaries, multiplication before rounding, a below-tie amount, exact decimal multiplication, zero and empty totals, and five invalid inputs.

Common mistakes

  • Lost scale: BigDecimal is immutable, so save the value returned by setScale. A MathContext controls precision in significant digits; it is not the same as asking for two decimal places.
  • Misleading comparisons: equals considers both value and scale, so 0.3 and 0.30 are different under equals. Use compareTo when you only care about numeric value. The test runner uses equals deliberately because the output contract includes two places.
  • Invalid input: the fixture rejects 1,25, 1e2, 1.23456 and negative prices before parsing, and rejects zero quantity. If your interface accepts localized numbers, parse and validate that format before passing normalized decimal text to this logic.
  • Totals do not reconcile: if the printed lines are rounded individually but a different rule computes the subtotal, the displayed sum can differ. Define and test how the application represents that difference rather than hiding it with formatting.

The fixture uses two decimal places and HALF_UP to make a visible comparison. A real billing system must choose its precision, rounding stage and reconciliation rules from its own requirements; this example does not model taxes, discounts, currency conversion or returns. Keep a regression fixture where the two boundaries differ, because ordinary whole-cent prices may never expose a misplaced rounding step.