Programming Search⌘K

Patterncore

Money

Also called Money pattern, money type, monetary amount.

Money is a value object for an amount and its currency. It keeps exact amounts, refuses to add different currencies, and splits an amount with no lost cents.

Family
architectural
Intent
Represent a monetary value as an amount and a currency, with exact arithmetic.

Intent

The Money pattern "Represents a monetary value."1 A money object has an amount and a currency. It does exact arithmetic, it refuses to mix currencies, and it splits an amount so that no part of a cent is lost.

Problem

Many programs calculate with money, but most languages have no money type. A program that keeps money in a plain number has two problems. The catalog names the first: "you want to avoid adding your dollars to your yen without taking the currency differences into account".1 A number has no currency, so the language cannot stop the addition.

The second problem is rounding. "Monetary calculations are often rounded to the smallest currency unit. When you do this it's easy to lose pennies (or your local equivalent) because of rounding errors."1 Binary floating point makes this worse, because it cannot keep 0.10 exactly.

Solution

Make a Value object for money. The parts are:

  • The amount. Keep it in an exact type: an integer number of the minor unit, such as cents, or a decimal type. Never use a binary floating point number.
  • The currency. Each amount has its currency, such as an ISO 4217 code. The currency also tells how many digits the minor unit has.
  • Arithmetic that checks the currency. Addition and subtraction of two amounts with different currencies is an error. Conversion is a separate step with an exchange rate.
  • Allocation. To split an amount by ratios, give each part its share rounded down, then give the units that are left to the parts one by one. The sum of the parts is always the whole amount. The book shows this with 5 cents that must go 70% to one account and 30% to another.2
  • Equality by value. Two money objects are equal when the amount and the currency are equal.
  Money(1000, EUR) + Money(50, EUR)   -> Money(1050, EUR)   "10.50 EUR"
  Money(1000, EUR) + Money(500, JPY)  -> error: cannot add EUR and JPY
  Money(5, EUR).allocate([70, 30])    -> [Money(4, EUR), Money(1, EUR)]

In the following program, allocate splits amounts in minor units. 100.00 in three parts gives 33.34, 33.33 and 33.33, and 0.05 in the ratio 70 to 30 gives 0.04 and 0.01.

def allocate(units, ratios):
    total = sum(ratios)
    parts = [units * r // total for r in ratios]
    for i in range(units - sum(parts)):  # give the units that are left, one each
        parts[i] += 1
    return parts


print(allocate(10000, [1, 1, 1]))  # 100.00 in three parts
print(allocate(5, [70, 30]))  # 0.05 in the ratio 70 to 30
Output
[3334, 3333, 3333]
[4, 1]

Example

Each example has a Money value with an integer amount in the minor unit and a currency code. The program adds 0.50 EUR to 10.00 EUR. It tries to add 500 JPY to an amount in EUR and gets an error. It prints 500 JPY with no decimal point, because the yen has no minor unit. Then it splits 5 cents in the ratio 70 to 30, and 100 EUR in three equal parts. Last, it compares two equal amounts.

PythonGitHub
from dataclasses import dataclass

FRACTION_DIGITS = {"EUR": 2, "USD": 2, "JPY": 0}  # from ISO 4217


@dataclass(frozen=True)
class Money:
    units: int  # in the minor unit of the currency, such as cents; never a float
    currency: str

    def __add__(self, other):
        self._same_currency(other)
        return Money(self.units + other.units, self.currency)

    def _same_currency(self, other):
        if self.currency != other.currency:
            raise ValueError(f"cannot add {self.currency} and {other.currency}")

    def allocate(self, ratios):
        """Split by ratios. The sum of the parts is always the whole amount."""
        total = sum(ratios)
        parts = [self.units * r // total for r in ratios]
        for i in range(self.units - sum(parts)):  # the units that are left, one each
            parts[i] += 1
        return [Money(p, self.currency) for p in parts]

    def __str__(self):
        d = FRACTION_DIGITS[self.currency]
        if d == 0:
            return f"{self.units} {self.currency}"
        whole, frac = divmod(self.units, 10**d)
        return f"{whole}.{frac:0{d}d} {self.currency}"


def show(parts):
    return ", ".join(str(p) for p in parts)


a = Money(1000, "EUR")
b = Money(50, "EUR")
print("a:", a)
print("a + b:", a + b)
try:
    a + Money(500, "JPY")
except ValueError as e:
    print("error:", e)
print("fee:", Money(500, "JPY"))
print("5 cents 70/30:", show(Money(5, "EUR").allocate([70, 30])))
print("100 EUR in 3:", show(Money(10000, "EUR").allocate([1, 1, 1])))
print("equal:", "yes" if Money(1050, "EUR") == a + b else "no")
Output
a: 10.00 EUR
a + b: 10.50 EUR
error: cannot add EUR and JPY
fee: 500 JPY
5 cents 70/30: 0.04 EUR, 0.01 EUR
100 EUR in 3: 33.34 EUR, 33.33 EUR, 33.33 EUR
equal: yes
  • Verdict: idiom. Money is a frozen data class with an int amount in the minor unit and a currency code. Python integers have no fixed size, so the amount cannot overflow.
  • The standard library has decimal.Decimal for exact decimal amounts, but no money type. The table of fraction digits here has only the three currencies of the example.
JavaGitHub
import java.util.ArrayList;
import java.util.Currency;
import java.util.List;
import java.util.stream.Collectors;

public class Main {
    // units: in the minor unit of the currency, such as cents. A record gives equals and hashCode.
    record Money(long units, Currency currency) {
        static Money of(long units, String code) {
            return new Money(units, Currency.getInstance(code));
        }

        Money plus(Money other) {
            if (!currency.equals(other.currency)) {
                throw new IllegalArgumentException("cannot add " + currency + " and " + other.currency);
            }
            return new Money(Math.addExact(units, other.units), currency);
        }

        // Split by ratios. The sum of the parts is always the whole amount.
        List<Money> allocate(long... ratios) {
            long total = 0;
            for (long r : ratios) total += r;
            long[] parts = new long[ratios.length];
            long left = units;
            for (int i = 0; i < ratios.length; i++) {
                parts[i] = units * ratios[i] / total;
                left -= parts[i];
            }
            for (int i = 0; left > 0; i++, left--) parts[i] += 1; // the units that are left, one each
            List<Money> out = new ArrayList<>();
            for (long p : parts) out.add(new Money(p, currency));
            return out;
        }

        @Override
        public String toString() {
            int d = currency.getDefaultFractionDigits(); // 2 for EUR, 0 for JPY
            if (d == 0) return units + " " + currency;
            long scale = (long) Math.pow(10, d);
            return String.format("%d.%0" + d + "d %s", units / scale, units % scale, currency);
        }
    }

    static String show(List<Money> parts) {
        return parts.stream().map(Money::toString).collect(Collectors.joining(", "));
    }

    public static void main(String[] args) {
        Money a = Money.of(1000, "EUR");
        Money b = Money.of(50, "EUR");
        System.out.println("a: " + a);
        System.out.println("a + b: " + a.plus(b));
        try {
            a.plus(Money.of(500, "JPY"));
        } catch (IllegalArgumentException e) {
            System.out.println("error: " + e.getMessage());
        }
        System.out.println("fee: " + Money.of(500, "JPY"));
        System.out.println("5 cents 70/30: " + show(Money.of(5, "EUR").allocate(70, 30)));
        System.out.println("100 EUR in 3: " + show(Money.of(10000, "EUR").allocate(1, 1, 1)));
        System.out.println("equal: " + (Money.of(1050, "EUR").equals(a.plus(b)) ? "yes" : "no"));
    }
}
Output
a: 10.00 EUR
a + b: 10.50 EUR
error: cannot add EUR and JPY
fee: 500 JPY
5 cents 70/30: 0.04 EUR, 0.01 EUR
100 EUR in 3: 33.34 EUR, 33.33 EUR, 33.33 EUR
equal: yes
  • Verdict: stdlib. java.util.Currency gives the ISO 4217 code and the default number of fraction digits, and the record adds the amount. Math.addExact throws an exception on overflow.
  • For amounts with more digits than a long holds, or for rates, use BigDecimal.
JavaScriptGitHub
const FRACTION_DIGITS = { EUR: 2, USD: 2, JPY: 0 }; // from ISO 4217

class Money {
  // units: an integer in the minor unit of the currency, such as cents.
  constructor(units, currency) {
    if (!Number.isSafeInteger(units)) throw new Error("units must be an integer");
    this.units = units;
    this.currency = currency;
    Object.freeze(this);
  }

  plus(other) {
    if (this.currency !== other.currency) {
      throw new Error(`cannot add ${this.currency} and ${other.currency}`);
    }
    return new Money(this.units + other.units, this.currency);
  }

  equals(other) {
    return this.units === other.units && this.currency === other.currency;
  }

  // Split by ratios. The sum of the parts is always the whole amount.
  allocate(ratios) {
    const total = ratios.reduce((s, r) => s + r, 0);
    const parts = ratios.map((r) => Math.floor((this.units * r) / total));
    let left = this.units - parts.reduce((s, p) => s + p, 0);
    for (let i = 0; left > 0; i++, left--) parts[i] += 1; // the units that are left, one each
    return parts.map((p) => new Money(p, this.currency));
  }

  toString() {
    const d = FRACTION_DIGITS[this.currency];
    if (d === 0) return `${this.units} ${this.currency}`;
    const scale = 10 ** d;
    const frac = String(this.units % scale).padStart(d, "0");
    return `${Math.floor(this.units / scale)}.${frac} ${this.currency}`;
  }
}

const show = (parts) => parts.join(", ");

const a = new Money(1000, "EUR");
const b = new Money(50, "EUR");
console.log(`a: ${a}`);
console.log(`a + b: ${a.plus(b)}`);
try {
  a.plus(new Money(500, "JPY"));
} catch (e) {
  console.log("error:", e.message);
}
console.log(`fee: ${new Money(500, "JPY")}`);
console.log("5 cents 70/30:", show(new Money(5, "EUR").allocate([70, 30])));
console.log("100 EUR in 3:", show(new Money(10000, "EUR").allocate([1, 1, 1])));
console.log("equal:", new Money(1050, "EUR").equals(a.plus(b)) ? "yes" : "no");
Output
a: 10.00 EUR
a + b: 10.50 EUR
error: cannot add EUR and JPY
fee: 500 JPY
5 cents 70/30: 0.04 EUR, 0.01 EUR
100 EUR in 3: 33.34 EUR, 33.33 EUR, 33.33 EUR
equal: yes
  • Verdict: idiom. JavaScript numbers are binary floating point, so the class keeps an integer number of minor units and checks it with Number.isSafeInteger. For larger amounts, use BigInt.
  • Intl.NumberFormat with style: "currency" can format an amount for a locale, but it does not do the arithmetic.
package main

import (
	"fmt"
	"strings"
)

var fractionDigits = map[string]int{"EUR": 2, "USD": 2, "JPY": 0} // from ISO 4217

// Money is a value: Units is in the minor unit of the currency, such as cents.
type Money struct {
	Units    int64
	Currency string
}

func (m Money) Plus(o Money) (Money, error) {
	if m.Currency != o.Currency {
		return Money{}, fmt.Errorf("cannot add %s and %s", m.Currency, o.Currency)
	}
	return Money{m.Units + o.Units, m.Currency}, nil
}

// Allocate splits by ratios. The sum of the parts is always the whole amount.
func (m Money) Allocate(ratios ...int64) []Money {
	var total int64
	for _, r := range ratios {
		total += r
	}
	parts := make([]Money, len(ratios))
	left := m.Units
	for i, r := range ratios {
		parts[i] = Money{m.Units * r / total, m.Currency}
		left -= parts[i].Units
	}
	for i := 0; left > 0; i, left = i+1, left-1 { // the units that are left, one each
		parts[i].Units++
	}
	return parts
}

func (m Money) String() string {
	d := fractionDigits[m.Currency]
	if d == 0 {
		return fmt.Sprintf("%d %s", m.Units, m.Currency)
	}
	scale := int64(1)
	for i := 0; i < d; i++ {
		scale *= 10
	}
	return fmt.Sprintf("%d.%0*d %s", m.Units/scale, d, m.Units%scale, m.Currency)
}

func show(parts []Money) string {
	s := make([]string, len(parts))
	for i, p := range parts {
		s[i] = p.String()
	}
	return strings.Join(s, ", ")
}

func main() {
	a := Money{1000, "EUR"}
	b := Money{50, "EUR"}
	fmt.Println("a:", a)
	sum, _ := a.Plus(b)
	fmt.Println("a + b:", sum)
	if _, err := a.Plus(Money{500, "JPY"}); err != nil {
		fmt.Println("error:", err)
	}
	fmt.Println("fee:", Money{500, "JPY"})
	fmt.Println("5 cents 70/30:", show(Money{5, "EUR"}.Allocate(70, 30)))
	fmt.Println("100 EUR in 3:", show(Money{10000, "EUR"}.Allocate(1, 1, 1)))
	eq := "no"
	if (Money{1050, "EUR"}) == sum {
		eq = "yes"
	}
	fmt.Println("equal:", eq)
}
Output
a: 10.00 EUR
a + b: 10.50 EUR
error: cannot add EUR and JPY
fee: 500 JPY
5 cents 70/30: 0.04 EUR, 0.01 EUR
100 EUR in 3: 33.34 EUR, 33.33 EUR, 33.33 EUR
equal: yes
  • Verdict: idiom. Money is a struct of an int64 amount and a currency code, so == compares two amounts. The standard library has no money or decimal type.
  • %0*d takes the width from an argument, so the format works for any number of fraction digits.
RustGitHub
use std::fmt;

// From ISO 4217.
fn fraction_digits(currency: &str) -> u32 {
    match currency {
        "JPY" => 0,
        _ => 2,
    }
}

// units: in the minor unit of the currency, such as cents.
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
struct Money {
    units: i64,
    currency: &'static str,
}

impl Money {
    fn new(units: i64, currency: &'static str) -> Money {
        Money { units, currency }
    }

    fn plus(self, other: Money) -> Result<Money, String> {
        if self.currency != other.currency {
            return Err(format!("cannot add {} and {}", self.currency, other.currency));
        }
        Ok(Money::new(self.units + other.units, self.currency))
    }

    // Split by ratios. The sum of the parts is always the whole amount.
    fn allocate(self, ratios: &[i64]) -> Vec<Money> {
        let total: i64 = ratios.iter().sum();
        let mut parts: Vec<Money> = ratios.iter().map(|r| Money::new(self.units * r / total, self.currency)).collect();
        let left = self.units - parts.iter().map(|p| p.units).sum::<i64>();
        for p in parts.iter_mut().take(left as usize) {
            p.units += 1; // the units that are left, one each
        }
        parts
    }
}

impl fmt::Display for Money {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let d = fraction_digits(self.currency);
        if d == 0 {
            return write!(f, "{} {}", self.units, self.currency);
        }
        let scale = 10_i64.pow(d);
        write!(f, "{}.{:0w$} {}", self.units / scale, self.units % scale, self.currency, w = d as usize)
    }
}

fn show(parts: &[Money]) -> String {
    parts.iter().map(|p| p.to_string()).collect::<Vec<_>>().join(", ")
}

fn main() {
    let a = Money::new(1000, "EUR");
    let b = Money::new(50, "EUR");
    println!("a: {}", a);
    let sum = a.plus(b).unwrap();
    println!("a + b: {}", sum);
    if let Err(e) = a.plus(Money::new(500, "JPY")) {
        println!("error: {}", e);
    }
    println!("fee: {}", Money::new(500, "JPY"));
    println!("5 cents 70/30: {}", show(&Money::new(5, "EUR").allocate(&[70, 30])));
    println!("100 EUR in 3: {}", show(&Money::new(10000, "EUR").allocate(&[1, 1, 1])));
    println!("equal: {}", if Money::new(1050, "EUR") == sum { "yes" } else { "no" });
}
Output
a: 10.00 EUR
a + b: 10.50 EUR
error: cannot add EUR and JPY
fee: 500 JPY
5 cents 70/30: 0.04 EUR, 0.01 EUR
100 EUR in 3: 33.34 EUR, 33.33 EUR, 33.33 EUR
equal: yes
  • Verdict: idiom. Money derives PartialEq, Eq and Hash, and Copy makes it a value. The standard library has no money or decimal type.
  • take(left as usize) gives one more unit to each of the first parts, which is the same rule as the other examples.

Consequences

Benefits.

  • No lost cents. Integer or decimal amounts are exact, and allocation keeps the whole amount.
  • No mixed currencies. The money type finds an addition of two currencies when the program runs, or when it compiles in a language with a type for each currency.
  • One place for the rules. Rounding, formatting and allocation are in one class, and not copied in each calculation.
  • Clearer code. A parameter of type Money tells more than a number. The code smell Primitive Obsession describes the opposite.

Liabilities.

A float amount loses a cent when it is split. In the following program, 100.00 is split into three parts with round. Each part is 33.33, so the sum is 99.99, and one cent is gone.

This code runs but gives a wrong answer on purpose.

total = 100.00  # a float amount
shares = [round(total / 3, 2) for _ in range(3)]
print("shares:", shares)
print("sum of the shares:", round(sum(shares), 2))
Output
shares: [33.33, 33.33, 33.33]
sum of the shares: 99.99

Keep the amount as 10000 cents, and allocate the cents that are left after the division to the first parts, as allocate does.

More work for each operation. Multiplication by a rate, such as a tax rate, needs a rounding rule. The rule depends on the business and sometimes on the law, so the class must make it explicit.

Overflow. An integer amount of a fixed size can overflow for very large amounts. Use a checked addition or a type with no fixed size. See Integer overflow or wraparound.

Storage. The database needs both the amount and the currency. A money object is usually saved as an Embedded Value in two columns of the row of its owner.

When not to use it

When the amount is not money for the program. A price that the program only shows, and never adds, can stay a string from the source.

When the platform already has a money type. If a library or a framework of the program has a tested money type, use it and do not write a second one.

Decimal amounts. A decimal type is an alternative to integer minor units. "Decimal numbers can be represented exactly."3 The Python documentation adds that "In decimal floating point, 0.1 + 0.1 + 0.1 - 0.3 is exactly equal to zero", and for this reason "decimal is preferred in accounting applications".3 A decimal amount still needs a currency and a rounding rule.

Currency data. Java has a class for the currency. It says: "Currencies are identified by their ISO 4217 currency codes."4 Its method getDefaultFractionDigits "Gets the default number of fraction digits used with this currency."4 For example, "the default number of fraction digits for the Euro is 2, while for the Japanese Yen it's 0."4

Related patterns. Money is a Value object: it is immutable and equal by value. A Domain model uses money objects for prices, balances and totals. The Floating-point arithmetic page explains why 0.1 has no exact binary form.

Known uses

  • The Java Currency class gives ISO 4217 codes and fraction digits, and its documentation recommends BigDecimal for monetary values.4
  • The Python decimal module gives exact decimal arithmetic for amounts.3

References

  1. Martin Fowler, Catalog of Patterns of Enterprise Application Architecture, Money, pattern summary
  2. Martin Fowler, Patterns of Enterprise Application Architecture, Addison-Wesley, 2002, Chapter 18, Base Patterns, Money
  3. Python documentation, decimal, Decimal fixed-point and floating-point arithmetic, introduction
  4. Java SE 21 API, java.util.Currency, class description and getDefaultFractionDigits

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/RJ6CRP/text.yaml