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.
Where it lives
Section titled “Where it lives”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.
The packages decimal, money and units are in the core module. They use the standard library
(math/big) beyond the framework’s own httpfw/openapi (schemas), so they add no module requirement.
Compare money with Equal, not ==.
Decimals
Section titled “Decimals”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.
decimal.Decimal is the counterpart of BigDecimal: an unscaled big.Int and a scale, with the same
rules. Go has no built-in decimal and a general library was rejected (its division uses a
package-global precision and its string form drops trailing zeros), so this is a small type on
math/big.
d := decimal.MustParse("3132.40")fmt.Println(d, d.Scale()) // 3132.40 2_, err := decimal.Parse("1e3") // VALIDATION DECIMAL_INVALID: not a plain decimal number
q, err := decimal.MustParse("1").Div(decimal.MustParse("3"), 4, decimal.HalfEven)fmt.Println(q, err) // 0.3333 <nil>Round(scale, mode) is Java’s setScale. The modes are decimal.Up, Down, Ceiling, Floor,
HalfUp, HalfDown and HalfEven (ParseRoundingMode("HALF_EVEN") reads the Java names).
Div(o, scale, mode) is BigDecimal.divide(o, scale, mode); DivExact succeeds only when the
quotient terminates and gives it the smallest scale. Cmp and Equal are numeric: 2.0 equals
2.00.
A Decimal marshals as text (JSON writes a string and refuses a number), implements sql.Scanner and
driver.Valuer (read NUMERIC as text) and openapi.SchemaProvider. The zero value is 0.
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.
total := money.MustParse("0.40", "ZAR").Times(decimal.MustParse("7831.2"))fmt.Println(total) // 3132.480 ZARfmt.Println(total.Round(decimal.HalfEven)) // 3132.48 ZARRound(mode) rounds to the currency’s minor units. Plus, Minus, Cmp and money.Sum return an
error for two currencies. money.CurrencyOf("ZAR") and MinorUnits() read the table.
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.
Allocation
Section titled “Allocation”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");ratios := []decimal.Decimal{decimal.MustParse("1"), decimal.MustParse("1"), decimal.MustParse("1")}parts, err := money.MustParse("100.00", "ZAR").Allocate(ratios, decimal.HalfEven)fmt.Println(parts, err) // [33.34 ZAR 33.33 ZAR 33.33 ZAR] <nil>Exchange rates
Section titled “Exchange rates”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"));money.NewExchangeRate(from, to, rate, asOf) and Convert(m, mode).
Units and quantities
Section titled “Units and quantities”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);The units are variables (units.KGM, units.TNE, units.MTQ, units.C62, units.XPX, …), or
units.Parse("kg") for a code or alias. units.Builtin().With("KILO", units.KGM) makes a registry
with a partner’s spelling. The dimensions are units.Mass, Length, Area, Volume, Count,
Temperature and PackagingDim.
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");q := units.MustParseQuantity("7831.2", "KGM")got, err := q.To(units.TNE, 6, decimal.HalfEven) // 7.831200 TNE_, err = q.ToExact(units.LBR) // VALIDATION CONVERSION_INEXACT: the exact result does not terminateplus 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).
Packaging
Section titled “Packaging”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));p, _ := units.NewPackaging(units.C62)p, _ = p.Level(units.XCT, 24)p, _ = p.Level(units.XPX, 40)parts, err := p.Breakdown(units.MustParseQuantity("1000", "C62"))fmt.Println(parts, err) // [1 XPX 1 XCT 16 C62] <nil>Prices per unit and chargeable weight
Section titled “Prices per unit and chargeable weight”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"));price, _ := units.NewUnitPrice(money.MustParse("0.40", "ZAR"), units.KGM)charge, err := price.TimesExact(units.MustParseQuantity("7.8312", "TNE"))fmt.Println(charge, err) // 3132.480 ZAR <nil>Times(q, scale, mode) is the rounded form (one rounding).
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.
air, _ := units.KgPerCubicMetre(decimal.MustParse("167"))w, err := units.ChargeableWeight(units.MustParseQuantity("100", "KGM"), units.MustParseQuantity("1", "MTQ"), air, 0, decimal.HalfEven)fmt.Println(w, err) // 167 KGM <nil>units.Divisor(decimal.MustParse("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.