std::money
Money: an exact amount in a currency. A Money pairs a Decimal
amount with a Currency (std::currency), so payment, invoicing and
exchange-rate libraries share one type:
total = Money"12.50 EUR" Money.format(total, Locale"en") // "€12.50" Money.format(total, Locale"pl") // "12,50 €"
Money"12.50 EUR" is Money{amount: 12.50d, currency: Currency"EUR"}:
the amount, one space and the currency, as Display writes it, checked
when the program is checked. Build Money{...} from the fields when the
amount or the currency is a value the program computes.
The amount keeps every digit it has: adding, subtracting and multiplying
by a count are exact, and only Money.round and Money.multiply_by, a
product with a Decimal rate, round, to the currency’s minor digits.
Money.split and Money.allocate divide an amount into parts that sum
to it exactly, a bill shared three ways or 70 to 30. Two amounts in
different currencies do not add, so Money has no + or -:
Money.add, Money.subtract, Money.sum, Money.min and Money.max
return Err(CurrencyMismatch) for them. * by an Int count always has
an answer, so it is an operator: price * 3. Std has no exchange rates;
a library that has them converts and checks the currency first.
Money.format writes an amount as a reader of a locale writes it, and
Money.parse_in reads one back, strictly by default.
Import with import std::money.
Exports
Section titled “Exports”struct Money
Section titled “struct Money”struct Money amount: Decimal currency: Currency end
An exact amount in a currency. Two amounts are equal when their
currencies are and their amounts are equal as numbers: 12.5 and
12.50 euros are one amount. Display gives the amount and the
currency as its literal writes them, 12.50 EUR, the same in every
locale.
price = Money"12.50 EUR"
assert Display.to_string(price) == "12.50 EUR"
assert price == Money{amount: 12.50d, currency: Currency"EUR"}
assert price == Money"12.5 EUR"
Money.format
Section titled “Money.format”fn format(money: Money, locale: Locale, display: CurrencyDisplay = CurrencyDisplay.Symbol, sign: CurrencySign = CurrencySign.Standard) -> String
type function on Money
The amount as a reader of locale writes it, with the currency where
the locale’s pattern puts it. The amount shows the currency’s minor
digits, more when it has more, and never loses one: format a rounded
amount (Money.round) to round it. A symbol made of letters is kept
apart from the digits (BTC 0.50000000). sign: .Accounting writes
it in the locale’s accounting pattern (CurrencySign), which a
Name display has none of.
eur = Money"12.5 EUR"
assert Money.format(eur, Locale"en") == "€12.50"
assert Money.format(eur, Locale"pl") == "12,50\u{a0}€"
assert Money.format(eur, Locale"de", display: .Code) == "12,50\u{a0}EUR"
assert Money.format(eur, Locale"en", display: .Name) == "12.50 euros"
assert Money.format(Money"1234 JPY", Locale"ja") == "¥1,234"
assert Money.format(Money"2 EUR", Locale"en", display: .Name) == "2.00 euros"
assert Money.format(Money"5 USD", Locale"en-CA") == "US$5.00"
assert Money.format(Money"5 USD", Locale"en-CA", display: .Narrow) == "$5.00"
assert Money.format(Money"0.5 BTC:8", Locale"en") == "BTC\u{a0}0.50000000"
debit = Money"-10 USD"
assert Money.format(debit, Locale"en") == "-$10.00"
assert Money.format(debit, Locale"en", sign: .Accounting) == "($10.00)"
assert Money.format(Money"10 USD", Locale"en", sign: .Accounting) == "$10.00"
assert Money.format(Money"-10 EUR", Locale"de", sign: .Accounting) == "-10,00\u{a0}€"
Money.round
Section titled “Money.round”fn round(money: Money, mode: RoundingMode = RoundingMode.HalfEven) -> Money
type function on Money
The amount rounded to its currency’s minor digits, half to even
unless mode says otherwise: what a conversion or a share of a bill
rounds to before it is charged.
assert Money.round(Money"53.90875 EUR") == Money"53.91 EUR"
assert Money.round(Money"0.125 EUR") == Money"0.12 EUR"
assert Money.round(Money"0.125 EUR", mode: RoundingMode.HalfUp) == Money"0.13 EUR"
assert Money.round(Money"99.5 JPY") == Money"100 JPY"
Money.multiply_by
Section titled “Money.multiply_by”fn multiply_by(price: Money, factor: Decimal, mode: RoundingMode = RoundingMode.HalfEven) -> Money
type function on Money
The amount times a Decimal factor, rounded to its currency’s minor
digits with mode (half to even unless it says otherwise), as
Money.round rounds: a tax, a discount or a share of a bill.
* takes only an Int. A whole count times an amount is exact, so
three of a book’s price needs no rounding. A Decimal factor makes
more digits than the currency has, and the rounding that removes
them should be in the code where a reader sees it. There is no Float
form: a Float is binary, so 0.1 is not one tenth. Convert a Float
rate first, with Float.to_decimal(rate, 4, RoundingMode.HalfEven).
To refuse a product with more digits than the currency, round it
with Decimal.round_exact.
import std::float.Float
assert Money.multiply_by(Money"19.99 EUR", 0.23d) == Money"4.60 EUR"
assert Money.multiply_by(Money"0.25 EUR", 0.5d) == Money"0.12 EUR"
assert Money.multiply_by(Money"0.25 EUR", 0.5d, RoundingMode.HalfUp) == Money"0.13 EUR"
assert Money.multiply_by(Money"999 JPY", 0.08d) == Money"80 JPY"
assert Money.multiply_by(Money"-10.05 EUR", 0.5d) == Money"-5.02 EUR"
rate = Float.to_decimal(0.0825, 4, RoundingMode.HalfEven)?
assert Money.multiply_by(Money"40.00 USD", rate) == Money"3.30 USD"
Money.abs
Section titled “Money.abs”fn abs(money: Money) -> Money
type function on Money
The amount without its sign, in the same currency, every digit kept.
assert Money.abs(Money"-12.50 EUR") == Money"12.50 EUR"
assert Money.abs(Money"3 PLN") == Money"3 PLN"
Money.negate
Section titled “Money.negate”fn negate(money: Money) -> Money
type function on Money
The amount with its sign flipped, in the same currency: a refund of a charge. Negating zero stays zero.
assert Money.negate(Money"12.50 EUR") == Money"-12.50 EUR"
Money.sign
Section titled “Money.sign”fn sign(money: Money) -> Int
type function on Money
The sign of the amount as -1, 0, or +1, as Decimal.sign gives it:
a debit, nothing, or a credit.
assert Money.sign(Money"-0.01 EUR") == -1
assert Money.sign(Money"0.00 EUR") == 0
assert Money.sign(Money"12.50 EUR") == 1
Money.is_zero
Section titled “Money.is_zero”fn is_zero(money: Money) -> Bool
type function on Money
Whether the amount is zero, at any scale and in any currency.
assert Money.is_zero(Money"0.00 EUR")
refute Money.is_zero(Money"0.01 EUR")
Money.min
Section titled “Money.min”fn min(a: Money, b: Money) -> Result<Money, CurrencyMismatch>
type function on Money
The lesser of two amounts in one currency (ties return a): what a
refund is capped at. Amounts in two currencies are
Err(CurrencyMismatch); write ! after it where the currencies are
known to match.
assert Money.min(Money"12.50 EUR", Money"20 EUR") == Ok(Money"12.50 EUR")
assert Money.min(Money"12.50 EUR", Money"20 PLN")
== Err(CurrencyMismatch{left: Currency"EUR", right: Currency"PLN"})
Money.max
Section titled “Money.max”fn max(a: Money, b: Money) -> Result<Money, CurrencyMismatch>
type function on Money
The greater of two amounts in one currency (ties return a): a
minimum charge. Amounts in two currencies are
Err(CurrencyMismatch), as for Money.min.
assert Money.max(Money"0.30 EUR", Money"0.50 EUR")! == Money"0.50 EUR"
Money.add
Section titled “Money.add”fn add(a: Money, b: Money) -> Result<Money, CurrencyMismatch>
type function on Money
The sum of two amounts in one currency, exact, or
Err(CurrencyMismatch) for amounts in two currencies. Money has no
+, since a sum of two currencies has no answer; write ? after it
to pass the mismatch on, or ! where the currencies are known to
match.
assert Money.add(Money"12.50 EUR", Money"0.75 EUR") == Ok(Money"13.25 EUR")
assert Money.add(Money"12.50 EUR", Money"1 PLN")
== Err(CurrencyMismatch{left: Currency"EUR", right: Currency"PLN"})
Money.subtract
Section titled “Money.subtract”fn subtract(a: Money, b: Money) -> Result<Money, CurrencyMismatch>
type function on Money
a less b, exact, or Err(CurrencyMismatch) for amounts in two
currencies, as for Money.add.
assert Money.subtract(Money"12.50 EUR", Money"20 EUR") == Ok(Money"-7.50 EUR")
assert Money.subtract(Money"1 EUR", Money"1 USD") |> Result.is_err()
Money.sum
Section titled “Money.sum”fn sum(amounts: Iter<Money>, currency: Currency) -> Result<Money, CurrencyMismatch>
type function on Money
The sum of amounts, every one in currency: a cart’s total. No
amounts sum to zero in currency, so an empty cart’s total is in
the currency the shop charges in. The first amount in another
currency is Err(CurrencyMismatch), with currency on the left.
prices = [Money"12.50 EUR", Money"3 EUR"]
assert Money.sum(prices, Currency"EUR") == Ok(Money"15.50 EUR")
empty: List<Money> = []
assert Money.sum(empty, Currency"EUR") == Ok(Money"0 EUR")
assert Money.sum([Money"1 EUR", Money"2 USD"], Currency"EUR")
== Err(CurrencyMismatch{left: Currency"EUR", right: Currency"USD"})
Money.parse
Section titled “Money.parse”fn parse(text: String) -> Result<Money, Error>
type function on Money
The money text writes: the amount, one space and the currency, as
Display writes them and a Money"…" literal reads its text.
The amount is what String.to_decimal reads and keeps every digit
written, and the currency is what Currency.parse reads, so a custom
one names its minor digits. Otherwise the Error says what is wrong,
as a compile error at a literal of the text does. Use it for text the
program reads while it runs; a literal is checked when the program is
checked.
assert Money.parse("12.50 EUR") == Ok(Money"12.50 EUR")
assert Money.parse("1200 PTS:0") == Ok(Money"1200 PTS:0")
assert Money.parse("12.50") == Err(Error.NoCurrency{amount: "12.50"})
assert Money.parse("12,50 EUR") == Err(Error.Amount{text: "12,50"})
assert Money.parse("12.50 EUR") == Err(Error.Malformed{text: "12.50 EUR"})
assert Err(error) = Money.parse("5 BTC")
assert "${error}" == "`BTC` is not an ISO 4217 currency: a custom currency names its minor digits, as Money\"5 BTC:2\""
Money.parse_in
Section titled “Money.parse_in”fn parse_in(text: String, locale: Locale, currency: Currency, lenient: Bool = False) -> Result<Money, NumberParseError>
type function on Money
Read an amount in currency that a reader of locale wrote, strictly
unless lenient: True. Strict reads what Money.format writes, with
the currency’s symbol, narrow symbol or code where the locale puts
it, and the allowances Decimal.parse_in makes. Lenient also takes
the symbol or code on either side, or none, and what lenient number
parsing takes. Either way a different currency is WrongCurrency,
and more digits after the decimal point than the currency has is
TooManyFractionDigits.
eur = Currency"EUR"
assert Money.parse_in("12,50 €", Locale"pl", eur) == Ok(Money"12.50 EUR")
assert Money.parse_in("€1,299.50", Locale"en", eur) == Ok(Money"1299.50 EUR")
assert Money.parse_in("12,50", Locale"pl", eur, lenient: True) == Ok(Money"12.50 EUR")
assert Money.parse_in("12,50 zł", Locale"pl", eur)
== Err(NumberParseError.WrongCurrency{expected: eur, found: "zł"})
assert Money.parse_in("€12.505", Locale"en", eur)
== Err(NumberParseError.TooManyFractionDigits{max: 2})
Money.split
Section titled “Money.split”fn split(money: Money, n: PositiveInt) -> List<Money>
type function on Money
The amount split into n parts that sum to it exactly and differ by
at most one minor unit: a bill shared by n people. The leftover
units go one each to the first parts, so the larger parts come first,
as Money.allocate gives them out. It is Money.allocate with n
equal ratios. n is a PositiveInt, so there is at least one part.
assert Money.split(Money"100.00 EUR", 3) == [Money"33.34 EUR", Money"33.33 EUR", Money"33.33 EUR"]
assert Money.split(Money"5 JPY", 2) == [Money"3 JPY", Money"2 JPY"]
assert Money.split(Money"-0.05 USD", 2) == [Money"-0.03 USD", Money"-0.02 USD"]
assert Money.split(Money"0.01 EUR", 3) == [Money"0.01 EUR", Money"0.00 EUR", Money"0.00 EUR"]
Money.allocate
Section titled “Money.allocate”fn allocate(money: Money, ratios: Ratios) -> List<Money>
type function on Money
The amount split into parts proportional to ratios, one part per
ratio, that sum to it exactly: a payment shared 70 to 30, or a
discount spread over a cart’s lines by their prices. Each part is its
share rounded toward zero to a minor unit; the units left over go one
each to the parts in the order of ratios, skipping a zero ratio, so
a zero ratio’s part is always zero. This is Fowler’s allocate, as
Ruby Money and Dinero.js give it, and Decimal.allocate at the
currency’s minor digits.
A minor unit is the currency’s (a cent in EUR, a yen in JPY), or
the amount’s last digit when it has more: 0.125 EUR is split in
thousandths, so the parts still sum to it. A part has that many
digits. ratios are Ratios (std::decimal), so an empty list, a
negative ratio, or ratios that are all zero are compile errors in a
literal, and ratios computed when the program runs go through
Ratios.try_from.
assert Money.allocate(Money"100.00 EUR", [1, 1, 1]) == [
Money"33.34 EUR",
Money"33.33 EUR",
Money"33.33 EUR",
]
assert Money.allocate(Money"0.05 USD", [3, 7]) == [Money"0.02 USD", Money"0.03 USD"]
assert Money.allocate(Money"10 EUR", [70, 0, 30]) == [Money"7 EUR", Money"0 EUR", Money"3 EUR"]
assert Money.allocate(Money"0.01 EUR", [0, 1, 1]) == [Money"0 EUR", Money"0.01 EUR", Money"0 EUR"]
assert Money.allocate(Money"0.125 EUR", [1, 1]) == [Money"0.063 EUR", Money"0.062 EUR"]
assert Money.allocate(Money"-1 USD", [1, 2]) == [Money"-0.34 USD", Money"-0.66 USD"]
Money.multiply
Section titled “Money.multiply”impl Multiply<Int, Money> for Money
fn multiply(money: Money, rhs: Int) -> Money
impl Multiply.multiply
The amount times a count, exact: three of a book’s price.
assert Money"12.50 EUR" * 3 == Money"37.50 EUR"
Money.localize
Section titled “Money.localize”impl Localize for Money
fn localize(money: Money, locale: Locale) -> String
impl Localize.localize
The amount as Money.format writes it, with the currency’s symbol.
Money.from_fragments
Section titled “Money.from_fragments”impl Literal for Money
fn from_fragments(fragments: List<Fragment<String>>) -> Result<Money, Error>
Money"12.50 EUR" is Money{amount: 12.50d, currency: Currency"EUR"}: the amount, one space and the currency, as Display
writes them. The amount keeps every digit written, as a Decimal
literal does (Money"12.5 EUR" has one), and the currency is
what Currency"…" reads, so a custom one names its minor digits
(Money"1200 PTS:0"). A literal without slots is checked when the program
is checked, so a malformed amount, an unknown currency or a missing
one is a compile error at the literal, whose Error names what is
wrong and shows the form: typed literal Money"12.50" is invalid: `12.50` has no currency: write the amount, one space and the currency, as Money"12.50 EUR". The amount is what String.to_decimal reads:
an optional sign, digits, _ separators and an optional fraction.
The literal does not interpolate: Money"${amount} USD" is
Err(Interpolated) when it runs, whose message says to build
Money{...} from the fields.
assert Money"1299.50 USD" == Money{amount: 1299.50d, currency: Currency"USD"}
assert Money"-5.00 USD".amount == -5.00d
assert Money"1200 PTS:0".currency == Currency"PTS:0"
assert Decimal.scale(Money"12.5 EUR".amount) == 1
Money.to_string
Section titled “Money.to_string”impl Display for Money
fn to_string(money: Money) -> String
impl Display.to_string
The amount, every digit, one space and the currency as its literal
writes it: 12.50 EUR, or 1200 PTS:0 for a custom currency. A
Money"…" literal of the text is the same amount.
assert Display.to_string(Money"-5.00 USD") == "-5.00 USD"
assert Display.to_string(Money"1200 PTS:0") == "1200 PTS:0"
Money.inspect
Section titled “Money.inspect”impl Debug for Money
fn inspect(value: Money) -> String
impl Debug.inspect
Money.equal
Section titled “Money.equal”impl Equatable for Money
fn equal(a: Money, b: Money) -> Bool
impl Equatable.equal
Money.hash
Section titled “Money.hash”impl Hashable for Money
fn hash(value: Money) -> Int
impl Hashable.hash
enum Error
Section titled “enum Error”enum Error Malformed { text: String } Amount { text: String } NoCurrency { amount: String } NotACurrency { amount: String, error: currency.Error } Interpolated end
Why the text of a Money"…" literal, or Money.parse’s, is not an
amount in a currency.
Variants
-
Malformedtextis not an amount, one space and a currency. -
Amounttext, before the space, is not an amount: an optional sign, digits, and an optional.and more digits. -
NoCurrencyamountis an amount with no currency after it. -
NotACurrencyThe text after the amount
amountis not a currency;errorsays why. -
InterpolatedThe literal interpolates a value, which a
Moneyliteral does not.
Error.to_string
Section titled “Error.to_string”impl Display for Error
fn to_string(e: Error) -> String
impl Display.to_string
What is wrong, as a compile error at a Money"…" literal shows it.
assert Display.to_string(
Error.NoCurrency{amount: "12.50"}
) == "`12.50` has no currency: write the amount, one space and the currency, as Money\"12.50 EUR\""
Error.inspect
Section titled “Error.inspect”impl Debug for Error
fn inspect(value: Error) -> String
impl Debug.inspect
Error.equal
Section titled “Error.equal”impl Equatable for Error
fn equal(a: Error, b: Error) -> Bool
impl Equatable.equal
struct CurrencyMismatch
Section titled “struct CurrencyMismatch”struct CurrencyMismatch left: Currency right: Currency end
Two amounts in different currencies, which do not add, subtract or
compare: what Money.add, Money.subtract, Money.sum, Money.min
and Money.max return for them. left is the first amount’s currency and
right the second’s.
CurrencyMismatch.to_string
Section titled “CurrencyMismatch.to_string”impl Display for CurrencyMismatch
fn to_string(m: CurrencyMismatch) -> String
impl Display.to_string
The two currencies, naming a custom currency with its digits so two
of one code are told apart (PTS:0 and PTS:2).
assert Display.to_string(CurrencyMismatch{left: Currency"EUR", right: Currency"PLN"})
== "the amounts are in two currencies, EUR and PLN"
CurrencyMismatch.inspect
Section titled “CurrencyMismatch.inspect”impl Debug for CurrencyMismatch
fn inspect(value: CurrencyMismatch) -> String
impl Debug.inspect
CurrencyMismatch.equal
Section titled “CurrencyMismatch.equal”impl Equatable for CurrencyMismatch
fn equal(a: CurrencyMismatch, b: CurrencyMismatch) -> Bool
impl Equatable.equal
enum CurrencyDisplay
Section titled “enum CurrencyDisplay”enum CurrencyDisplay Symbol Narrow Code Name end
How Money.format shows the currency: its Symbol (€, US$ or $
as the locale writes it), its Narrow symbol ($ for every dollar),
its Code (EUR), or its Name in the amount’s plural form (12.50 euros). A custom currency has no symbol or name in CLDR, so every
display writes its code.
CurrencyDisplay.inspect
Section titled “CurrencyDisplay.inspect”impl Debug for CurrencyDisplay
fn inspect(value: CurrencyDisplay) -> String
impl Debug.inspect
CurrencyDisplay.equal
Section titled “CurrencyDisplay.equal”impl Equatable for CurrencyDisplay
fn equal(a: CurrencyDisplay, b: CurrencyDisplay) -> Bool
impl Equatable.equal
enum CurrencySign
Section titled “enum CurrencySign”enum CurrencySign Standard Accounting end
How Money.format writes a negative amount: with the locale’s
Standard currency pattern (-$10.00 in en), or with its
Accounting one, which some locales write in parentheses (($10.00)
in en, as a ledger shows a debit) and most write as the standard
one. JavaScript’s Intl.NumberFormat calls this currencySign.
CurrencySign.inspect
Section titled “CurrencySign.inspect”impl Debug for CurrencySign
fn inspect(value: CurrencySign) -> String
impl Debug.inspect
CurrencySign.equal
Section titled “CurrencySign.equal”impl Equatable for CurrencySign
fn equal(a: CurrencySign, b: CurrencySign) -> Bool
impl Equatable.equal