Skip to content

Money and units

Exact values for logistics and supply chain: money in a currency, quantities in units of measure with the standard conversions, packaging levels, prices per unit and chargeable weight. Java and Go give the same result to the last digit; the vectors in conformance/measure/, written by Java and compared by Go, are the proof (Conformance). The rules are in the measure specification.

Nothing rounds unless you ask, nothing divides without a scale, and nothing goes through a floating-point number.

It is deliberately small. It is not a general money or units framework, and it has no exchange-rate provider, tax engine or rating engine; those are application concerns that sit on top of these types. Display formatting (locale-aware “R 3 132,48”) belongs to the UI layer (Internationalisation): these types only produce plain decimal text.

The module is framework-measure, with packages io.flowcatalyst.framework.measure.money and io.flowcatalyst.framework.measure.units. It depends on nothing but the JDK. The typed-operation mapper in framework-http depends on it and puts the types on the wire.

Text is plain decimal only (-?[0-9]+(\.[0-9]+)?: no exponent, grouping, + or locale), and keeps its scale (3132.40 stays 3132.40). Division always names a scale and a rounding mode, so an inexact division can never happen silently. Add and subtract take the larger scale, multiply adds them. The seven rounding modes are UP, DOWN, CEILING, FLOOR, HALF_UP, HALF_DOWN and HALF_EVEN.

Java uses BigDecimal directly. Decimals adds the rules the specification fixes:

assertThat(Decimals.format(Decimals.parse("3132.40"))).isEqualTo("3132.40");
assertThat(Decimals.format(Decimals.parse("007.5"))).isEqualTo("7.5");
assertThat(Decimals.divide(Decimals.parse("1"), Decimals.parse("3"), 4, RoundingMode.HALF_EVEN))
.hasToString("0.3333");

The modes are java.math.RoundingMode’s. A failure is a MeasureException (an IllegalArgumentException) whose code() is one of the codes below.

The error codes are shared: DECIMAL_INVALID, DIVISION_BY_ZERO, CURRENCY_UNKNOWN, CURRENCY_MISMATCH, SUM_EMPTY, ALLOCATION_INVALID, UNIT_UNKNOWN, DIMENSION_MISMATCH, NO_CONVERSION, CONVERSION_INEXACT, TEMPERATURE_NOT_ADDITIVE, UNIT_NOT_IN_PACKAGING, PACKAGING_INVALID and RATE_INVALID. In Go every failure is a *decimal.Error (a leaf type of that package) with Code(), Status() (400), Message() and Details(), so it satisfies the HTTP error interface without importing it; each package exports its codes as constants (decimal.CodeDecimalInvalid, money.CodeCurrencyMismatch, units.CodeUnitUnknown, …). In a request body a bad value is a 400 with the code at the property’s path (rate: CURRENCY_UNKNOWN: unknown currency code), in both languages.

Currency is an ISO 4217 code with its minor units, from the table conformance/measure/iso4217.json (generated from the JDK’s currency list; codes with no defined fraction, such as precious metals, are left out). Both languages embed the same file, so an unknown code is CURRENCY_UNKNOWN in both. Money is a decimal amount and a currency.

Money rate = Money.parse("0.40", "ZAR");
Money total = rate.times(d("7831.2"));
assertThat(total.amount()).hasToString("3132.480");
assertThat(total.round(RoundingMode.HALF_EVEN).amount()).hasToString("3132.48");

round(mode) rounds to the currency’s minor units, round(scale, mode) to any scale. plus, minus, compareTo and Money.sum(list) work within one currency.

Mixing currencies is CURRENCY_MISMATCH, never a conversion; the sum of an empty list is SUM_EMPTY. Equality is numeric: 10.0 ZAR equals 10.00 ZAR. Money keeps its full precision until something rounds it: nothing rounds implicitly.

allocate splits an amount across consignments, legs or invoice lines so the parts add up to the whole. The amount is rounded to minor units first, each part is the floor of its share, and the leftover minor units go one each to the parts in order (a part with a zero ratio stays zero; a negative amount is allocated as its absolute value, every part negated).

List<Money> parts = Money.parse("100.00", "ZAR").allocate(List.of(d("1"), d("1"), d("1")), RoundingMode.HALF_EVEN);
assertThat(parts).extracting(m -> m.amount().toPlainString()).containsExactly("33.34", "33.33", "33.33");

ExchangeRate(from, to, rate, asOf) converts and rounds to the target currency. There is no rate provider: the application decides where rates come from (a bank feed, a contract rate, a daily table) and stores the rate it used next to the converted amount.

ExchangeRate rate = new ExchangeRate(Currency.of("USD"), Currency.of("ZAR"), d("18.3456"), Instant.parse("2026-11-03T00:00:00Z"));
assertThat(rate.convert(Money.parse("100.00", "USD"), RoundingMode.HALF_EVEN)).isEqualTo(Money.parse("1834.56", "ZAR"));

A Unit is identified by its UN/ECE Recommendation 20 common code (KGM, TNE, MTQ, LTR, C62), the form on the wire; the symbol is for people. The built-in table is conformance/measure/units.json (42 units): mass, length, area, volume, count, temperature and packaging units, every factor an exact fraction (1 lb is exactly 0.45359237 kg). Parsing accepts the code (case-sensitive) or an alias (case-insensitive: kg, m3, L, degC, PX); an application adds its partners’ spellings to a registry, and the built-in table cannot change.

assertThat(Unit.of("kg")).isEqualTo(Unit.KGM);
UnitRegistry registry = UnitRegistry.builtin().with("KILO", Unit.KGM);
assertThat(registry.parse("kilo")).isEqualTo(Unit.KGM);

A Quantity is a value and a unit. Conversion is computed exactly and rounded once, in one of two forms: to(unit, scale, mode) rounds, toExact(unit) does not and fails with CONVERSION_INEXACT when the result does not terminate (kilograms to pounds). Another dimension is DIMENSION_MISMATCH.

(d("7.8312") is new BigDecimal("7.8312") and q("7.8312", Unit.TNE) is new Quantity(d("7.8312"), Unit.TNE): two test helpers.)

assertThat(q("7831.2", Unit.KGM).to(Unit.TNE, 6, RoundingMode.HALF_EVEN)).isEqualTo(q("7.831200", Unit.TNE));
assertThat(q("1", Unit.LBR).toExact(Unit.KGM).value()).hasToString("0.45359237");

plus and minus convert the right-hand side to the left’s unit exactly first; compareTo compares across units of one dimension (1000 GRM and 1 KGM compare equal but are not equals). Temperature is affine (the table carries an offset): it converts (100 °C is 212 °F) but is never added or multiplied (TEMPERATURE_NOT_ADDITIVE).

How many eaches a pallet holds depends on the product, so the framework does not know it: the application supplies a packaging per product. Packaging units (XPX pallet, XCT carton, XCS case, XBX box, …) convert only through one. convert and convertExact work between any two levels; breakdown returns every level, largest first, with any fractional rest at the smallest. A unit that is not a level is UNIT_NOT_IN_PACKAGING; a bad level (a count of zero, a repeated unit, a first unit that is not a count or mass unit) is PACKAGING_INVALID.

Packaging p = Packaging.of(Unit.C62).level(Unit.XCT, 24).level(Unit.XPX, 40);
assertThat(p.convertExact(q("1", Unit.XPX), Unit.C62)).isEqualTo(q("960", Unit.C62));
assertThat(p.breakdown(q("1000", Unit.C62))).containsExactly(q("1", Unit.XPX), q("1", Unit.XCT), q("16", Unit.C62));

A unit price is a rate: 0.40 ZAR per KGM. Multiplying converts the quantity to the price’s unit, multiplies and rounds the money once; the exact form is unrounded.

UnitPrice price = new UnitPrice(Money.parse("0.40", "ZAR"), Unit.KGM);
assertThat(price.timesExact(q("7.8312", Unit.TNE)).amount()).hasToString("3132.480");
assertThat(price.times(q("7.8312", Unit.TNE), 2, RoundingMode.HALF_EVEN)).isEqualTo(Money.parse("3132.48", "ZAR"));

Chargeable weight is the larger of the actual weight and volume x factor, in KGM. It is the calculation every freight rating repeats, and easy to get wrong with floats. The factor is a density factor, in either form the trade uses: kilograms per cubic metre (167) or a divisor in cm³ per kg (6000).

Quantity light = ChargeableWeight.of(q("100", Unit.KGM), q("1", Unit.MTQ), DensityFactor.kgPerCubicMetre(167), 0, RoundingMode.HALF_EVEN);
assertThat(light).isEqualTo(q("167", Unit.KGM));

DensityFactor.divisor(6000) is the other form.

On the wire, in OpenAPI and in the database

Section titled “On the wire, in OpenAPI and in the database”

Typed operations write and read the types as JSON (Typed operations and OpenAPI):

Type JSON
Money {"amount": "3132.48", "currency": "ZAR"}
Quantity {"value": "7831.2", "unit": "KGM"}
UnitPrice {"price": {...}, "per": "KGM"}
Currency, Unit their code, as a string

Amounts and values are always JSON strings, never numbers, so no value ever passes through a float, and they keep their scale. Reading applies the constructors’ validation (a JSON number, an unknown or a missing member is refused), and a failure is reported with the specification’s code at the property’s path. The OpenAPI document has the components Money, Quantity and UnitPrice (closed objects, amounts string with format: decimal, the currency ^[A-Z]{3}$) and Currency and Unit as strings.

In the database a value is two columns by convention: <field>_amount NUMERIC and <field>_currency CHAR(3), <field>_value NUMERIC and <field>_unit VARCHAR(8). Composing the pair is the caller’s code. In Go Currency and Unit also implement sql.Scanner and driver.Valuer for text columns.