Skip to content

Decimal Value Contracts

The Course
•
25 min study

Exact arithmetic is not enough: values also need an equality policy and accepted range. BigDecimal.compareTo compares numerical value, while equals includes scale. A small validated record can normalize representation at one boundary so callers do not repeat those decisions.

Understand the contract

The numbers "2.0" and "2.00" compare as numerically equal but have different representations. Consequently compareTo returns zero while equals returns false. This matters in record equality and hash-based collections, which use equals. Do not assume a zero comparison result means every collection will treat two objects as the same key.

signum() returns -1 for a negative value, 0 for zero, and 1 for a positive value. It answers the sign question without converting the decimal to int or double.

Our Amount record normalizes values to scale two. RoundingMode.UNNECESSARY requires that this can be done exactly: "2.000" is accepted as 2.00, but "2.001" is rejected rather than silently rounded. A negative amount is rejected too. ArithmeticException from the scale operation is converted into an input-validation IllegalArgumentException with its cause preserved. Null is rejected before any method call.

The record deliberately represents nonnegative amounts in one unspecified currency, not general monetary quantities with exchange rates. The later ledger rejects zero expenses, while a total may legitimately be zero. Separating those contracts prevents accidentally forbidding empty reports.

Before running, write the output you expect and explain which rule produces each line. Each editor is an independent program.

Predict, then run Java
import java.math.BigDecimal;

public class Main {
    public static void main(String[] args) {
        BigDecimal shortForm = new BigDecimal("2.0");
        BigDecimal longForm = new BigDecimal("2.00");
        System.out.println(shortForm.equals(longForm));
        System.out.println(shortForm.compareTo(longForm) == 0);
        System.out.println(shortForm.setScale(2).equals(longForm));
    }
}
Check your prediction
Text
false
true
true

setScale(2) with no rounding mode only works when no digits are lost: on 2.0 it pads to 2.00, but on 2.555 it throws ArithmeticException. That makes it a check as well as a normalization, and the examples in this course rely on it for amounts that should already have at most two places. When a value may legitimately need rounding, pass a RoundingMode and say so in the contract.

Trace a different case

Normalize in the compact constructor before Java stores the record component. The generated equals then sees normalized BigDecimal values. This is useful only if normalization matches the domain: changing numerical value by rounding would be a different contract. This example catches the expected validation category while allowing programming defects to remain visible.

Compare the boundary case Java
import java.math.BigDecimal;
import java.math.RoundingMode;

public class Main {
    public static void main(String[] args) {
        System.out.println(new Amount(new BigDecimal("2.0")).equals(new Amount(new BigDecimal("2.00"))));
        try {
            new Amount(new BigDecimal("2.001"));
        } catch (IllegalArgumentException expected) {
            System.out.println("Fraction rejected");
        }
    }
}

record Amount(BigDecimal value) {
    Amount {
        if (value == null || value.signum() < 0) {
            throw new IllegalArgumentException("nonnegative amount required");
        }
        try {
            value = value.setScale(2, RoundingMode.UNNECESSARY);
        } catch (ArithmeticException error) {
            throw new IllegalArgumentException("at most two meaningful decimal places", error);
        }
    }
}
Check your prediction
Text
true
Fraction rejected

Choose the comparison that answers the question

Numerical comparison and representation equality are separate questions. compareTo asks whether one amount is smaller, equal or larger in value. equals asks whether its BigDecimal representation also has the same scale. A map using equals and a report using compareTo may therefore make different distinctions without either operation being defective.

The normalized record resolves that difference for this domain by storing exactly two places. Check both an equivalent spelling such as 2.000 and a genuinely extra fraction such as 2.001. UNNECESSARY accepts the former because no value is lost, while it rejects the latter.

If another domain needs three meaningful decimal places, create or change its contract deliberately. Do not globally round a shared value object simply because one report wants fewer displayed digits.

Debug a plausible mistake

The comparison above was one call. Collections make the same choice for you: HashSet and HashMap use equals and hashCode, so they inherit BigDecimal's scale-sensitive equality without any visible comparison in your code.

Exercise

Repair the distinct price count

A price list arrives as text from several systems, so the same price is spelled differently: 2.0 and 2.00, 3 and 3.000. The report must count distinct prices by value, so this list must print Distinct prices: 3 (2, 3 and 3.50). Predict what the current program prints before changing it. Do not convert to double. The supplied version compiles; its behavior is the problem.

Debugging workspace Java
import java.math.BigDecimal;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class Main {
    public static void main(String[] args) {
        List<String> prices = List.of("2.0", "2.00", "3", "3.000", "3.50");
        Set<BigDecimal> distinct = new HashSet<>();
        for (String price : prices) {
            distinct.add(new BigDecimal(price));
        }
        System.out.println("Distinct prices: " + distinct.size());
    }
}
Hint 1: the idea

HashSet decides "already present" with equals, and BigDecimal's equals also compares scale. 2.0 has scale 1 and 2.00 has scale 2, so the set keeps both.

Hint 2: a first step

Give every value the same representation before it reaches the set, the way the Amount record does in its constructor. Keep the rounding mode that refuses to change a value.

Show one solution
Java
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class Main {
    public static void main(String[] args) {
        List<String> prices = List.of("2.0", "2.00", "3", "3.000", "3.50");
        Set<BigDecimal> distinct = new HashSet<>();
        for (String price : prices) {
            distinct.add(new BigDecimal(price).setScale(2, RoundingMode.UNNECESSARY));
        }
        System.out.println("Distinct prices: " + distinct.size());
    }
}

Expected output after repair:

Text
Distinct prices: 3

The original printed 5: every spelling was its own member, because equals treats 2.0 and 2.00 as different. Normalizing to scale two before add makes equal values equal representations, so the set's equals matches the report's question. UNNECESSARY keeps the repair honest: a price such as 2.001 would throw instead of being rounded into a match. A TreeSet, which uses compareTo, would also count 3, but then the set and a later HashMap of the same values would disagree; normalizing once avoids that.

Build it yourself

Exercise

Decimal Value Contracts: practice

Create record Rate(BigDecimal value) accepting values from 0 through 1 inclusive, with at most two meaningful decimal places. Normalize to scale two; reject null, out-of-range values and extra fractional precision. Check 0.5 equals 0.50, 1 is accepted as 1.00, and 1.01 is rejected. Print Rate checks passed. signum() returns negative/zero/positive for a negative/zero/positive value.

Your workspace Java
public class Main {
    public static void main(String[] args) {
        // Add your implementation and checks below.
        System.out.println("Your workspace");
    }
}
Hint 1: the idea

Use numerical comparisons for the range, then normalize the representation for generated equality.

Hint 2: a first step

Check signum and compareTo(BigDecimal.ONE) before setScale with UNNECESSARY.

Show one solution
Java
import java.math.BigDecimal;
import java.math.RoundingMode;

public class Main {
    public static void main(String[] args) {
        check("normalized", new Rate(new BigDecimal("0.5")).equals(new Rate(new BigDecimal("0.50"))));
        check("upper bound", new Rate(BigDecimal.ONE).value().equals(new BigDecimal("1.00")));
        try {
            new Rate(new BigDecimal("1.01"));
            throw new AssertionError("rate above one accepted");
        } catch (IllegalArgumentException expected) {
            // Expected domain rejection.
        }
        System.out.println("Rate checks passed");
    }

    static void check(String name, boolean condition) {
        if (!condition) {
            throw new AssertionError(name);
        }
    }
}

record Rate(BigDecimal value) {
    Rate {
        if (value == null || value.signum() < 0 || value.compareTo(BigDecimal.ONE) > 0) {
            throw new IllegalArgumentException("rate outside range");
        }
        try {
            value = value.setScale(2, RoundingMode.UNNECESSARY);
        } catch (ArithmeticException error) {
            throw new IllegalArgumentException("rate precision", error);
        }
    }
}

Expected output:

Text
Rate checks passed

The range is checked with signum and compareTo before any rescaling, because those ask about value; setScale(2, UNNECESSARY) then fixes the representation so the generated equals makes 0.5 and 0.50 equal. Order matters for 1.001: it is above one, so it is reported as out of range rather than as a precision error. The 1.01 check proves the upper bound is inclusive of 1 only.

Change it and test again

Add checks for 0, -0.01, 0.001 and 0.500. Predict which are valid before running. Replace UNNECESSARY with HALF_UP temporarily: which rejected case now slips through? Restore exact validation. Numeric range and representational precision are independent rules and need independent checks.

Explain before moving on

Why does normalizing scale make record equality easier to use here? If callers need three-place rates, which contract and tests must change? Avoid changing a shared type's normalization rule merely to satisfy one report's display preference.

Was this article helpful?

Your response is saved on this device.