Skip to content

Money

std::money has Money, an amount in a currency. The amount is a Decimal, so it is exact. The currency is a Currency from std::currency.

Money"19.99 USD" is an amount of US dollars: the amount, one space and the currency’s ISO 4217 code. Interpolating a Money writes the same text. Both fields are public, so when the amount comes from a variable, build the value from its fields with Money{...}:

import
    std::currency.Currency
    std::io
    std::money.Money
end

fn main()
    price = Money"19.99 USD"
    io.print(price)
    dbg price.amount
    dbg price.currency

    cents = 1999
    amount = Int.to_decimal(cents) / 100d
    dbg Money{amount:, currency: Currency"USD"} == price
end

The compiler checks a Money literal, so a missing currency, an unknown code or a malformed amount is an error before the program runs:

import std::money.Money

fn main()
    price = Money"19.99"
    dbg price
end

Money.parse("19.99 EUR") reads the same text while the program runs, and returns that error as a value.

The amount keeps every digit you write, as a Decimal does. Money"12.5 USD" and Money"12.50 USD" are equal, but only the second has two digits after the point.

* multiplies an amount by an Int. Adding and subtracting are functions that return a Result, since dollars and euros don’t add: Money.add and Money.subtract take two amounts, and Money.sum adds a list of them. It takes the currency too, so the sum of an empty list is zero in that currency. Nothing is lost to rounding:

import
    std::currency.Currency
    std::io
    std::money.{CurrencyMismatch, Money}
end

fn main() -> Result<Unit, CurrencyMismatch>
    book = Money"12.50 USD"
    pen = Money"2.35 USD"

    io.print(Money.add(book, pen)?)
    io.print(Money.subtract(book, pen)?)
    io.print(book * 3)
    io.print(Money.sum([book, pen, pen], Currency"USD")?)

    empty: List<Money> = []
    io.print(Money.sum(empty, Currency"USD")?)
    Ok(Unit)
end

Adding dollars to euros gives a number with no meaning, so it is an Err(CurrencyMismatch), which names both currencies. Here main passes it on with ?, and the program stops with it:

import
    std::io
    std::money.{CurrencyMismatch, Money}
end

fn main() -> Result<Unit, CurrencyMismatch>
    price = Money"12.50 USD"
    fee = Money"2.00 EUR"
    total = Money.add(price, fee)?
    io.print(total)
    Ok(Unit)
end

Convert one amount first, with a rate your program gets from somewhere it trusts. Where the currencies are known to match, as for two literals, write ! after the call instead of ?. Money.min and Money.max return a Result the same way.

Money keeps every digit until you round it. A third of $10.00 is $3.333333 to six places, and it stays that way through more arithmetic. Money.round rounds an amount to its currency’s digits: two for the dollar, none for the yen.

import
    std::io
    std::money.Money
end

fn main()
    total = Money"10.00 USD"
    third = {..total, amount: .. |> Decimal.divide(3d, 6, .HalfEven)}
    io.print(third)
    io.print(Money.round(third))

    io.print(Money.round(Money"0.125 USD"))
    io.print(Money.round(Money"0.135 USD"))
    io.print(Money.round(Money"0.125 USD", mode: .HalfUp))
    io.print(Money.round(Money"1234.5 JPY"))
end

A tie, an amount exactly halfway like 0.125, rounds to the even digit by default: 0.12, and 0.135 to 0.14. Rounding every tie up would make a long list of rounded amounts add up to a little more than the exact total. Rounding to even sends half the ties down and half up, so the errors cancel out. Pass mode: for another rule, such as .HalfUp, when a law or a contract asks for it.

Three rounded thirds of $10.00 make $9.99, so a bill split that way loses a cent. Money.split gives parts that sum to the amount exactly, the leftover cent going to the first part, and Money.allocate splits by ratios:

import
    std::io
    std::money.Money
end

fn main()
    io.print(Money.split(Money"10.00 USD", 3))
    io.print(Money.allocate(Money"10.00 USD", [70, 30]))
end

A plain Decimal splits the same way, to the number of digits you name: Decimal.split(100d, 3, 2) is [33.34d, 33.33d, 33.33d], and Decimal.allocate takes ratios.

A shop may count in something that isn’t money in a bank, such as loyalty points. A custom currency has its own code and says how many digits it has after the point: PTS:0 has none.

A module lists the custom currencies it writes in its nomi.toml, in the [money] section, and then writes them in Currency and Money literals the same way. A currency built from text the program reads while it runs needs no listing.

This example is a small project of two files; each tab is one file:

// FILE: main.nomi
import
    std::currency.Currency
    std::io
    std::money.Money
end

fn main()
    points = Money.add(Money"1200 PTS:0", Money"300 PTS:0")!
    io.print(points)
    io.print(Money.format(points, Locale"en-US"))
    dbg Currency.parse("PTS:0") == Ok(points.currency)
end

// FILE: nomi.toml
[module]
name = "shop"
entry_points = ["main"]

[money]
custom_currencies = ["PTS:0"]

Two custom currencies are equal when their codes and digits are, so two libraries that each write PTS:0 share one currency. PTS:0 and PTS:2 are two currencies, and adding them is an Err. A custom currency can’t reuse an ISO code, and has no symbol, so Money.format writes its code.

A custom currency needs no other setup, so the list is what catches a typo. A literal naming a custom currency the module doesn’t list is an error when the program is checked, and it suggests a listed one that is close. With PTS:0 listed, Money"5 PST:0" is:

error: typed literal Money"5 PST:0": `PST:0` is a custom currency this module does not list: add it to [money].custom_currencies in nomi.toml
 --> main.nomi:7:14
  |
7 |     io.print(Money"5 PST:0")
  |              ^^^^^^^^^^^^^^
  = help: did you mean `PTS:0`? nomi.toml lists it

The custom currency list

  • Currency.custom("PST", 0) with both arguments written out is checked the same way as a literal.
  • Each module has its own list: a library lists the currencies it writes, and the application’s list doesn’t cover them.
  • A single file with no nomi.toml, like the other examples on this page, may write any custom currency.
  • [money] lists what an entry may hold, and std::currency what a custom currency can do.

Money.format writes a price the way a reader of a locale expects, with the currency’s symbol in the right place. How a locale writes numbers is in Locales & Formatting.

import
    std::io
    std::money.Money
end

fn main()
    price = Money"1299.5 USD"

    [Locale"en-US", Locale"de", Locale"fr"]
    |> Iter.each(fn locale -> io.print("${locale}: ${Money.format(price, locale)}"))

    dbg "${price}"
    dbg Money.format(Money"1500 JPY", Locale"ja")
end

The dollar sign comes before the amount in American English and after it in German and French. French writes $US, since several countries call their money a dollar. CLDR also knows how many digits each currency has after the decimal point. The dollar has two, so 1299.5 becomes 1,299.50. The yen has none.

Putting a Money in a string, as in "${price}", gives the amount and the code: 1299.5 USD, the text its literal is written in. Like a number in a string, it is the same for every reader.

display: picks how the currency is shown: its symbol (the default), its narrow symbol, its code, or its name.

import std::money.Money

fn main()
    usd = Money"5 USD"
    dbg Money.format(usd, Locale"en-US", display: .Code)
    dbg Money.format(usd, Locale"en-CA")
end

After USD is a no-break space, which dbg writes \u{a0}. Canadian English writes US$ for the US dollar, since $ alone would mean the Canadian dollar. display: .Narrow writes $5.00, for a page where the currency is clear, and .Name writes 5.00 US dollars. A custom currency has no symbol or name in CLDR, so it is always shown by its code.

Money.parse_in reads a price a person typed, written the way their locale writes prices, in the currency you name. By default the price must have the currency’s symbol or code where the locale puts it. lenient: True also takes the amount alone.

import
    std::currency.Currency
    std::money.Money
end

fn main()
    usd = Currency"USD"
    dbg Money.parse_in("$1,299.50", Locale"en-US", usd)
    dbg Money.parse_in("1299.50", Locale"en-US", usd, lenient: True)
    dbg Money.parse_in("€12.50", Locale"en-US", usd)
end

A price in another currency is an error, and so is one with more digits than the currency has: $12.505 is Err(TooManyFractionDigits{max: 2}). Locales & Formatting covers how each locale writes numbers, and the rest of what strict and lenient reading accept.

Money holds only an amount and a currency, with both fields public, so payment, invoicing and accounting libraries can share one type. Std has no exchange rates. A library that has them takes a Money, checks its currency, and returns a new Money in the other currency, rounded with Money.round when it is ready to charge.

Locales & Formatting is next. It writes an amount, and numbers, dates and lists, the way a reader’s language writes them.