Precision tests for Java BigDecimal arithmetic
BigDecimal gives Java code an exact base-10 representation of values such as 0.10, but its operations can still round or produce a scale the domain did not request. A result can be numerically close yet unusable for tax, interest, refunds or reconciliation. Precision tests should therefore check the value, the retained decimal places and the rounding policy instead of trusting a convenient equality assertion.
Australian billing and commerce add useful realism to the problem. The Australian dollar is normally presented in dollars and cents, while the standard GST rate is 10% under the A New Tax System (Goods and Services Tax) Act 1999. The Australian Consumer Law also governs clear and accurate price displays, so tax-inclusive and tax-exclusive calculations cannot be treated as interchangeable. Retail and engineering teams in Sydney and Melbourne routinely reconcile card-tap checkout totals with online orders and business invoices.
Precision and scale are easy to conflate. For new BigDecimal("12.50"), the unscaled value is 1250, the precision is 4 and the scale is 2. A MathContext caps precision by significant digits and selects rounding; it does not mean “two decimal places”. A setScale call changes the number of decimal places, but may still round if the chosen mode cannot preserve the value.
A useful precision suite layers hand-computed examples, boundary cases and properties that should hold after transformation. It covers the money path as well as parsing, formatting and reconciliation, because a lost digit often enters at one of those edges. Expected values should come from an independent rule or reference table, not from repeating the production calculation in the test.
Understand the decimal contract
Internally, BigDecimal stores an arbitrary-precision integer plus a scale, interpreted as the unscaled value multiplied by ten to the power of negative scale. That design avoids binary floating-point artefacts, but it does not remove business rounding. It also allows scales to grow when operations require them, so a displayed result and its stored representation may not have the same shape.
The natural scale rules are worth stating directly in tests: addition and subtraction use the greater operand scale, while multiplication adds operand scales. Thus 1.20 + 2.3 becomes 3.50, and 1.20 × 2.3 becomes 2.760. Neither should be silently normalised to two places unless that is the domain rule. Division may not terminate; a call without a MathContext or target scale can throw ArithmeticException.
Equality adds another layer. BigDecimal.equals considers scale, so 1.0 is not equal to 1.00, whereas compareTo reports numeric equality. Use compareTo when representation does not matter, and assert scale separately when it does. Avoid using stripTrailingZeros as a display operation: it can turn 1200.00 into scientific notation with a negative scale.
Test arithmetic with exact expectations
Start with exact expected values expressed as decimal strings. new BigDecimal("0.10") represents one tenth exactly; new BigDecimal(0.10) can preserve the awkward binary approximation held by a double. For a JUnit assertion, assertEquals(0, expected.compareTo(actual)) checks numeric equality without making scale part of equals. If the contract requires two cents, follow it with an explicit scale assertion rather than replacing the value check with string formatting.
Give each operation its own cases. Test addition and subtraction around zero, refunds and carried cents; multiplication with fractional and large factors; and division with exact, terminating and repeating quotients. A test for one third should verify either the specified rounding result or the exception, not whichever behaviour the current implementation happens to produce. Pinning the expected outcome exposes accidental changes in precision or scale.
Metamorphic checks strengthen the suite. Adding zero should preserve numeric value, multiplying by one should do the same, and rounding an already rounded amount should not change it again. For repeated calculations, compare the final result with a higher-precision intermediate and an independently rounded final value. This catches error that accumulates even when every individual assertion appears reasonable.
Cover rounding modes and monetary boundaries
Rounding is a domain decision, not merely a Java detail. HALF_UP sends exact halfway cases away from zero, while HALF_EVEN selects the even final digit; DOWN, CEILING and FLOOR serve different accounting policies. Australian GST, discounts and interest calculations must follow the method specified by the pricing rules and tax setup. A blanket assumption of HALF_UP may be wrong for an inherited or contract-defined rule.
Boundary values expose the policy fastest. Include zero, one cent, one tenth of a cent, half-cent ties, values just below and above a carry, negative refunds, very small inputs and values near an application limit. Run each case against every permitted rounding mode when the calculation library is shared. This matters in Australian payment flows, where card-tapped amounts and invoice totals must agree before a customer leaves the counter or receives an online receipt.
Rounding order can change the total. Three 0.335 items equal 1.005; rounding each item to cents produces 1.02 with HALF_UP, while rounding the aggregate produces 1.01. Decide whether the contract rounds each line, each invoice or an accumulated ledger balance, and test that choice explicitly. Also verify that repeated scaling remains stable, so an already final amount is not changed by a later formatting step.
Apply a precision-test checklist
A compact checklist separates arithmetic correctness from domain correctness:
Core arithmetic cases
- Assert numeric value independently, then check scale when the representation is contractual.
- Exercise zero, one-cent, half-cent, carry, negative-refund and large-amount boundaries.
- Give division an explicit scale and rounding mode, and expect failure when exactness is mandatory.
- Check invariants such as zero-addition, unit-multiplication and repeatable rounding.
The next layer protects the value as it crosses system boundaries:
Money-path and regression cases
- Derive expected Australian dollar results from tax, discount and refund rules, not from production helpers.
- Keep binary
doublevalues out of parsing and monetary conversion paths; use decimal text or integer minor units. - Reconcile rounded line totals with invoice totals and exercise both GST-inclusive and GST-exclusive examples.
- Preserve auditable transaction values used by AUSTRAC-regulated banks and payment providers.
Property-based generators can add constrained random values, but the oracle must remain independent. Use a rational or integer-minor-unit calculation for expected results, and retain the scale limits of the production domain. When a build step generates validators for decimal limits, compile-time annotation testing can verify the generated sources before those rules reach a service.
Compare strategies and retain the invariant
The main precision mechanisms differ in the property they protect:
| Approach | Property controlled | Strong use | Main risk |
|---|---|---|---|
| Exact operation | Exact value and natural scale | Addition, subtraction and multiplication | Division may throw, and the resulting scale may differ |
setScale with a rounding mode |
Decimal places and tie handling | Final invoice or account amount | Can discard digits if the policy is wrong |
MathContext |
Precision ceiling and rounding | Repeated or non-terminating calculations | Precision is significant digits, not cents |
compareTo |
Numeric equality | Reconciliation across systems | Hides a meaningful scale mismatch |
equals plus a scale assertion |
Numeric value and exact representation | Canonical ledger records | Requires an explicit scale policy |
Choose exact operations when later steps need every digit, but apply rounding only at a defined business boundary. Use setScale when the requirement is a fixed number of decimal places, and use a MathContext when a calculation truly needs a significant-digit budget. For comparisons, pair numeric equality with a scale check whenever scale carries contractual meaning. This keeps the test aligned with the rule rather than with one formatter’s output.
The rule to remember is simple: preserve exact arithmetic where the domain allows it, make every rounding decision explicit, and assert both the numeric result and any required scale.