> ## Documentation Index
> Fetch the complete documentation index at: https://docs.cockroachlabs.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Representing money

> Monetary amounts must be stored and computed exactly.

Monetary amounts must be stored and computed exactly. A rounding error of one cent per line, multiplied across many orders, becomes a reconciliation incident. This page gives the rules for storing and computing monetary amounts in CockroachDB. Each rule is presented as a titled recommendation with its rationale, the DDL or SQL, a nuance to account for, and the tradeoff.

The worked entities are `orders` and `order_lines`. Every rule is grounded in documented CockroachDB behavior. `DECIMAL` is CockroachDB's documented type for money, [`CHECK` constraints and `TIMESTAMPTZ` are supported standard SQL](https://docs.cockroachlabs.com/docs/stable/sql-feature-support), and the only arithmetic helper used is standard SQL `ROUND`.

## Use `DECIMAL`, never `FLOAT`

**Rule.** Store every monetary amount as `DECIMAL(precision, scale)`. Never use `FLOAT`, `REAL`, or `DOUBLE PRECISION` for money.

**Why.** [`DECIMAL` (aliases `DEC`, `NUMERIC`) stores exact fixed-point numbers](https://docs.cockroachlabs.com/docs/stable/decimal) and is CockroachDB's documented choice for money. `FLOAT` is binary floating point and **loses precision**: most decimal fractions have no exact binary representation, so the stored value is an approximation and errors compound under arithmetic.

```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
CREATE TABLE order_lines (
  order_id   UUID NOT NULL REFERENCES orders(id),
  line_no    INT  NOT NULL,
  sku        STRING NOT NULL,
  qty        INT  NOT NULL CHECK (qty > 0),
  currency   CHAR(3) NOT NULL,
  unit_price DECIMAL(18,2) NOT NULL CHECK (unit_price >= 0),
  discount   DECIMAL(18,2) NOT NULL DEFAULT 0 CHECK (discount >= 0),
  tax        DECIMAL(18,2) NOT NULL DEFAULT 0 CHECK (tax >= 0),
  PRIMARY KEY (order_id, line_no)
);
```

**The drift.** Adding ten dimes as `FLOAT` does not yield one dollar:

```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
SELECT 0.1::FLOAT + 0.2::FLOAT;   -- 0.30000000000000004
SELECT sum(x) FROM (VALUES
  (0.1::FLOAT),(0.1::FLOAT),(0.1::FLOAT),(0.1::FLOAT),(0.1::FLOAT),
  (0.1::FLOAT),(0.1::FLOAT),(0.1::FLOAT),(0.1::FLOAT),(0.1::FLOAT)) v(x);
-- 0.9999999999999999, not 1.00
```

The same computation in `DECIMAL` is exact:

```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
SELECT 0.1::DECIMAL + 0.2::DECIMAL;   -- 0.3
SELECT sum(x) FROM (VALUES (0.1::DECIMAL) /* ...ten times... */) v(x);  -- 1.0
```

A `FLOAT` subtotal of `0.9999999999999999` fails an equality check against the expected `1.00`, and display truncation turns it into `0.99`, a lost cent.

> [!WARNING]
>
> **Never store money in FLOAT**
> `FLOAT` is for measurements with tolerance, such as sensor readings or geodata, not for money. Accumulated binary drift cannot be reliably corrected by rounding after the fact. Choose `DECIMAL` at `CREATE TABLE` time.

**Nuance.** `DECIMAL(p,s)` **rounds to scale `s` on store, pads with zeros to `s`, and errors on precision overflow**. `19.999` stored into `DECIMAL(18,2)` becomes `20.00`. A value requiring more than `18 - 2 = 16` integer digits is rejected rather than silently truncated. Stored values must remain under 64KB; this limit is not reached by monetary amounts but exists. Treat store-time rounding as a safety net, not a rounding policy. See "Round deliberately."

**Tradeoff.** `DECIMAL` arithmetic is slower than hardware `FLOAT`, and each value is slightly larger on disk. For an OLTP order system this is not significant: performance is bound by transaction coordination and network latency, not by decimal multiplication. Correctness takes priority.

## Store the currency with every amount

**Rule.** Put a `currency CHAR(3)` column (ISO 4217, e.g. `USD`, `EUR`, `JPY`) next to every monetary column, or once per `orders` row when an order is single-currency. Never add two amounts of different currencies.

**Why.** A bare `DECIMAL` is a number, not money. `100.00` has no meaning without its unit. Summing `100.00 USD` and `100.00 JPY` yields an invalid `200.00`. The currency also determines **scale**, because the number of minor-unit digits is currency-dependent: USD and EUR have 2 (cents), JPY has 0 (no sen in practice), and some currencies (BHD, KWD) have 3.

```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
ALTER TABLE orders ADD COLUMN currency CHAR(3) NOT NULL DEFAULT 'USD'
  CHECK (currency = upper(currency) AND length(currency) = 3);

-- Guard: every line matches its order's currency (enforce in the write txn).
```

**Nuance.** Because scale is currency-dependent, `DECIMAL(18,2)` is correct for USD and EUR but **incorrect for JPY**, where 2 fractional digits imply a precision the currency does not have, and incorrect for BHD, which requires 3. For a single-currency system, pin the scale to that currency. For a multi-currency system, either carry a wider scale (for example, `DECIMAL(18,4)`) and round to the currency's minor unit at calculation time, or define a scale per currency and validate on write.

**Tradeoff.** A single scale across all currencies is simpler to model but stores meaningless trailing digits for JPY and cannot represent the full precision of 3-digit currencies at scale 2. A per-currency scale is exact but moves validation logic into the application or `CHECK` constraints. Choose based on whether the system is genuinely multi-currency; most order systems are effectively single-currency per order.

> [!NOTE]
>
> **Related standards**
> Currency codes here follow [ISO 4217](https://www.iso.org/iso-4217-currency-codes). When an order system exchanges payment and remittance data with banks or payment networks, that interchange is increasingly governed by [ISO 20022](https://www.iso20022.org/), the open standard for financial messaging across payments, securities, cards, and trade. Order management is not itself a messaging system, but the amounts, currencies, and references modeled here are the fields an ISO 20022 payment message carries. Keeping money exact and currency-tagged, as above, is what makes a clean mapping to those messages possible.

## Snapshot prices at order time

**Rule.** When a line is created, **copy** `unit_price`, `discount`, and `tax` onto the `order_lines` row. Never join to the live product/catalog/price table to compute a historical order's total.

**Why.** Prices change. A later price change must not retroactively alter what a customer was charged. An order is a contract fixed at purchase time. Its arithmetic must be reproducible from immutable data for refunds, disputes, audits, and tax filings, potentially years later.

```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
-- At checkout, snapshot the catalog price into the line (do NOT reference it live):
INSERT INTO order_lines (order_id, line_no, sku, qty, currency, unit_price, discount, tax)
SELECT $1, $2, p.sku, $3, p.currency, p.price, $4, $5
FROM products p
WHERE p.sku = $6;
-- After this INSERT the line never reads products.price again.
```

The forbidden pattern, recomputing a past total against today's catalog:

```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
-- WRONG: a price change tomorrow silently rewrites yesterday's order total.
SELECT ol.qty * p.price
FROM order_lines ol JOIN products p ON p.sku = ol.sku
WHERE ol.order_id = $1;
```

**Nuance.** The snapshot must include every input to the price: unit price, per-line discount, tax amount, and currency. If the tax rate, not only the tax amount, can affect a later partial refund, snapshot the rate as well. The catalog is an input at one instant, not a source of truth for the order thereafter.

**Tradeoff.** Snapshotting duplicates data: the same `unit_price` exists in `products` and in many `order_lines` rows. This redundancy is intentional; it provides immutability and auditability. Storage is inexpensive relative to the cost of a corrupted audit trail.

## Round deliberately, in one place

**Rule.** Define one rounding rule and apply it explicitly with `ROUND` at a single stage: round tax per line, then sum lines into the order total. Do not rely on storage rounding to do it for you.

**Why.** `DECIMAL(p,s)` rounds to scale on store, but this is implicit and occurs wherever a value is written to a column, which removes control over when and how rounding happens. The rounding policy (half-up versus half-even) and the rounding stage (per line versus on the grand total) change the final cent. Defining the rule once, in explicit SQL, makes the total reproducible.

**Worked tax calculation (round-half-up, per line).** Line: `qty 3 × unit_price 19.99 − discount 5.00`, tax rate `8.25%`.

```
net   = 3 * 19.99 - 5.00        = 54.97
tax   = ROUND(54.97 * 0.0825)   = ROUND(4.535025) = 4.54   -- half-up to 2dp
line  = 54.97 + 4.54            = 59.51
```

```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
SELECT ROUND(54.97 * 0.0825, 2);   -- 4.54 (standard SQL ROUND)
```

**Nuance.** Rounding at the line and rounding on the summed total produce different results. `ROUND(sum(net) * rate)` is **not** equal to `sum(ROUND(net * rate))` in general, because rounding does not distribute over addition. Fix the stage in the specification. This page rounds per line, then sums, and computes the stored `order_lines.tax` the same way throughout.

**Tradeoff.** Per-line rounding matches what appears on an invoice line and is what customers and auditors verify against, but it accumulates up to half a cent of rounding per line compared with a single round on the total. Rounding only the total is marginally more accurate in aggregate but produces lines that do not sum to the printed total. Per-line rounding is the conventional and defensible choice for order lines.

## Totals are derived and checkable

**Rule.** The order total is a pure function of its lines: `sum(unit_price * qty - discount + tax)`. Store it for convenience, but treat it as derivable and verify it.

**Why.** A stored `orders.total` that diverges from its lines is a silent corruption. Because the total is derived, it can always be recomputed and checked for equality in the write transaction, in a background audit, or in tests.

```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
-- Verification: list any order whose stored total disagrees with its lines.
SELECT o.id, o.total AS stored,
       sum(ol.unit_price * ol.qty - ol.discount + ol.tax) AS computed
FROM orders o
JOIN order_lines ol ON ol.order_id = o.id
GROUP BY o.id, o.total
HAVING o.total <> sum(ol.unit_price * ol.qty - ol.discount + ol.tax);
-- Expect zero rows.
```

Enforce currency consistency on the same principle: every line's `currency` must equal the order's, so that the `sum` is meaningful.

**Nuance.** The verification is valid only if the lines were computed with the agreed rounding rule. Incorrect per-line `tax` values sum to a self-consistent but wrong total. The check guarantees *internal consistency*, not *policy correctness*; both this query and the rounding discipline above are required.

**Tradeoff.** Recomputing on every read is always correct but requires a join and aggregation. Storing `total` is fast to read but must be kept consistent with the lines by writing both in one transaction. Store the total and audit it; do not store it without verification.

## Worked multi-line order

One USD order, three lines, tax `8.25%`, round-half-up per line:

| line | sku | qty | unit\_price | discount | net | tax (ROUND net×0.0825) | line total |
| - | - | - | -: | -: | -: | -: | -: |
| 1 | WIDGET | 3 | 19.99 | 5.00 | 54.97 | 4.54 | 59.51 |
| 2 | GADGET | 1 | 149.00 | 0.00 | 149.00 | 12.29 | 161.29 |
| 3 | CABLE | 2 | 7.50 | 1.50 | 13.50 | 1.11 | 14.61 |

```
subtotal (net) = 54.97 + 149.00 + 13.50 = 217.47
total tax      =  4.54 +  12.29 +  1.11 =  17.94
order total    = 217.47 + 17.94         = 235.41
```

The verification query above returns zero rows: the stored `235.41` equals `sum(unit_price*qty - discount + tax) = 59.51 + 161.29 + 14.61 = 235.41` exactly, because every value is `DECIMAL`.

## Tradeoff: `DECIMAL` vs integer minor units

Some teams store money as an integer count of minor units, such as cents as `BIGINT`, instead of `DECIMAL`.

**Integer minor units: pros.** No fractional type is involved, so there is nothing to round on store. Arithmetic is integer math, which is fast and exact. It maps directly to payment-gateway and ledger APIs that operate in cents. Equality and summation are exact.

**Integer minor units: cons.** The scale is implicit and exists only in application code. `14900` has no meaning without the context "USD cents," and a currency with 0 or 3 minor digits (JPY, BHD) breaks the "divide by 100" assumption. Division and percentage math, such as tax and splits, still require a rounding decision, now in application code rather than readable SQL. Reports and ad-hoc SQL must divide by the correct power of ten in every query, and a single missed conversion is an off-by-100 error.

**Recommendation.** Use **`DECIMAL`**. It is CockroachDB's documented type for money, keeps the scale explicit in the schema, and supports tax and totals in readable SQL with `ROUND`. Integer minor units are reasonable for a thin pass-through to a cents-based ledger or gateway that is strictly single-currency with a fixed 2-digit minor unit and uses integer-only arithmetic throughout. For a general order-management system that computes discounts, taxes, and multi-line totals, `DECIMAL` is the default.
