Mehdi Akiki
Published on

Units, Currency, and Time Zones Belong in the Type or Contract

Authors
  • Mehdi Akiki avatar
    Name
    Mehdi Akiki
    Twitter

Reference

amount: 100 is not enough information.

It may mean 100 dollars, 100 cents, 100 kilograms, 100 milliseconds, or a local wall-clock value encoded as an integer. A nearby variable name can help one code path and still disappear when the value reaches JSON, SQL, a queue, or a spreadsheet.

I put the dimension into the type or the data contract.

A bare primitive moves ambiguity downstream

These interfaces compile and serialize:

calculateShipping(weight: number): number
schedule(at: string): void
charge(amount: number): void

They leave every important question to convention:

grams or kilograms?
instant or local civil time?
which time zone?
major or minor currency units?
which currency?
which rounding policy?

The error often appears far from the boundary. A value looks reasonable, so validation does not catch it.

Measurement values need quantity and unit

I use a representation like:

{
  "value": "12.50",
  "unit": "kg"
}

The unit code comes from a governed vocabulary. UCUM provides case-sensitive codes and composition rules for units used in science, engineering, and business.

Case can matter. m and M are not safe to normalize blindly. Neither are mg and Mg.

Inside one component, a strongly typed quantity can prevent mixing dimensions:

struct Grams(i64);
struct Millimeters(i64);

fn shipping_band(weight: Grams) -> Band { /* ... */ }

At an external boundary, I carry the unit even when the internal service has one canonical unit. This makes migrations and integrations visible.

Conversion needs precision and provenance

Converting is a business operation, not a string rename.

original value and unit
conversion rule or factor
rounding mode
precision retained
converted value and unit
conversion timestamp or version when relevant

For measurements, the factor may be exact while the chosen numeric representation is not. For sensor data, calibration and measurement uncertainty may matter more than decimal places.

I do not repeatedly convert back and forth. I preserve the observation and create a canonical projection for comparison.

Money is amount plus currency plus arithmetic policy

This payload is incomplete:

{ "price": 1999 }

A safer contract is explicit:

{
  "minor_amount": 1999,
  "currency": "EUR"
}

But “minor units” still needs a currency table and version. Not every currency convention uses two decimal digits, and formatting conventions can differ from settlement rules. Unicode CLDR's currency data and formatting specification records currency-specific digits and display behaviour.

For fractional calculations such as tax, allocation, or exchange, I also state:

calculation precision
rounding mode
where rounding occurs
which party receives remainder units
exchange-rate source and timestamp

I never add amounts with different currency codes. Conversion creates a new money value and an audit record; it is not ordinary addition.

An offset is not a time zone

This timestamp identifies an instant:

2026-11-18T09:00:00+01:00

It does not encode the future civil-time rules for a location. A recurring meeting at 09:00 in Casablanca needs a time-zone identity and local schedule, not only today's offset.

The IANA time-zone database records changing offset and daylight-saving rules for named regions. Governments can change those rules; therefore the same location may use a different offset on another date or after a database update.

I distinguish temporal types:

instant: one point on a global timeline
local date: calendar date without time
local date-time: wall-clock fields, not yet an instant
zoned date-time: local fields interpreted with a named zone and rules
duration: elapsed amount, not a calendar period
calendar period: one month/day according to a calendar

One timestamp column cannot safely represent all of them.

Local times can be ambiguous or nonexistent

During clock transitions, a local time can occur twice or not occur at all.

If a user asks for 02:30 in a named zone, the resolver may need a policy:

reject ambiguity and ask
choose earlier occurrence
choose later occurrence
shift through a nonexistent interval
skip this recurrence

I store the policy with recurring schedules. Choosing silently in a date library makes behaviour dependent on library defaults and versions.

For an executed event, I store the resolved instant. For the user's continuing intention, I also retain the local schedule and zone identifier.

The same-looking number needs a semantic type

These values are not interchangeable:

timeout_ms = 5000
occurred_at_epoch_ms = 5000
price_minor = 5000
distance_m = 5000
percentage_basis_points = 5000

A schema that validates all as integers proves representation, not meaning.

I use wrappers in application code and named objects at integration boundaries:

type DurationValue = { value: number; unit: "ms" | "s" };
type Money = { minorAmount: string; currency: string };
type ZonedSchedule = {
  localDateTime: string;
  timeZone: string;
  ambiguityPolicy: "earlier" | "later" | "reject";
};

Closed string unions are convenient but may require schema evolution when a valid new code appears. A governed string plus validation and an unsupported state can be safer at an open integration boundary.

Change the contract without guessing old values

Suppose an old field is named weight and producers disagree about kilograms versus grams. Renaming it to weight_grams does not repair history.

I migrate with evidence:

1. inventory producer versions and observed ranges
2. stop accepting new ambiguous writes
3. add explicit value + unit fields
4. dual-read old data with source-specific rules
5. backfill only records whose unit can be proven
6. mark the rest unknown or require review
7. compare old/new business outcomes
8. remove the ambiguous field after every reader migrates

Range heuristics can flag records for review. They should not silently invent a unit.

This is one reason Why Semantic Versioning Does Not Describe Data Compatibility: a structurally additive migration can still change the meaning of old records.

Failure examples I keep as contract tests

My boundary fixtures include:

  • 1000 g and 1 kg compare equal after conversion;
  • an unknown unit is rejected or quarantined, not treated as canonical;
  • unit-code case remains significant;
  • two currencies cannot be added without an explicit exchange operation;
  • a zero-decimal and a three-decimal currency follow their configured scales;
  • a recurring zoned schedule crosses an offset change correctly;
  • ambiguous local time follows the stored policy;
  • an instant round-trips without becoming server-local time;
  • conversion retains original value and evidence;
  • old ambiguous data stays unknown when the unit cannot be proved.

I test examples at serialization and database boundaries, not only constructors. Generic mappers are where semantic types often collapse back into primitives.

My boundary checklist

When I see a number or timestamp, I ask:

What dimension or temporal kind is this?
Where is its unit, currency, or zone recorded?
Can conversion lose precision or depend on a changing table?
What rounding and ambiguity policy applies?
Is the original observation preserved?
Can an unsupported code survive without a dangerous default?
Does the database type keep the same meaning?
How will old ambiguous values be migrated honestly?

Strong types inside one service are useful. Explicit contracts across services are essential. Once unit, currency, and temporal intent travel with the value, an integration can validate meaning instead of only accepting syntax.