# `ExchangeRate`

A rate between two currencies at an instant: one `from` is `rate` of `to`, written `GBP/EUR 1.17 2026-10-18T09:00:00Z`. An app holds one it was given; `money.convert` applies it.

[Money and banking](types.md#money-and-banking); not ordered; since Jadpo 0.1.0.

## Make one

Build one from its fields, `ExchangeRate { from: ...  to: ...  rate: ... }`.

`text.parse(raw, as: ExchangeRate)` reads one from its text; text that isn't one at all fails `malformed`, such as `GBP/EUR 1.17`, `GBP-EUR 1.17 2026-10-18T09:00:00Z` or `GBP/XYZ 1.17 2026-10-18T09:00:00Z`.

## Fields

| Field | Type |
|---|---|
| `from` | [`Currency`](type-currency.md) |
| `to` | [`Currency`](type-currency.md) |
| `rate` | `Decimal` |
| `at` | [`Instant`](type-instant.md) |

## Text, JSON and storage

`text.from` writes its canonical text, the one form `text.parse` reads back. JSON sends an object of its parts.

| Text | JSON |
|---|---|
| `GBP/EUR 1.17 2026-10-18T09:00:00Z` | `{"from":"GBP","to":"EUR","rate":"1.17","at":"2026-10-18T09:00:00Z"}` |
| `EUR/JPY 162.4031 2026-10-18T09:30:00Z` | `{"from":"EUR","to":"JPY","rate":"162.4031","at":"2026-10-18T09:30:00Z"}` |

It is stored in 4 columns, each named for the field, `_` and its suffix. This is `EUR/JPY 162.4031 2026-10-18T09:30:00Z`:

| Column | Type | Holds |
|---|---|---|
| `<field>_from` | `char(3)` | `'EUR'` |
| `<field>_to` | `char(3)` | `'JPY'` |
| `<field>_rate` | `numeric` | `162.4031` |
| `<field>_at` | `timestamptz(3)` | `'2026-10-18 09:30:00.000000+00'::timestamptz` |

## Shown to people

`text.format(value, locale:)` shows it to people in their locale.

With `locale: Locale.en_gb`:

| Value | Shown |
|---|---|
| `GBP/EUR 1.17 2026-10-18T09:00:00Z` | `GBP/EUR 1.17 2026-10-18T09:00:00Z` |
| `EUR/JPY 162.4031 2026-10-18T09:30:00Z` | `EUR/JPY 162.4031 2026-10-18T09:30:00Z` |

## Operations

- `money.convert(value: Money, rate: ExchangeRate) -> Money`: `value` in `rate`'s `to` currency, from its `from` one: the major units times `rate.rate`, rounded half to even to a minor unit, so £10.50 at a `GBP/EUR` rate of 1.17 is €12.28. It fails with `currency_mismatch` when `value` isn't in `rate.from`, unless that is known: an inverted rate is then a compile error. The rate is one the app holds; nothing here fetches one.

Like every standard type, it also has the contract's own operations: `text.parse`, `text.from`, `text.format`, `json.read`, `json.write` and `==`. It isn't ordered, so `<` and sorting don't take it. [Every standard type meets one contract](../topics/every-standard-type-meets-one-contract.md) says how they work.
