This resume is also available in English.

7. Pitfalls in practice5 / 5 · All columns

Columns › 7. Pitfalls in practice › Part 30

Handling Money in Go: Minor Units, Decimals, Currencies, Rounding and Allocation

Go 處理金額:整數分、decimal、幣別、四捨五入與分攤

Why money must never be a float64, and how to model it in Go as int64 minor units plus a currency: differing decimal places, JSON, rounding for tax and FX rates, allocation that never loses a cent, database columns and tests.

  • Go
  • Payments
In this article
  1. What this article solves
  2. Step 1: See exactly what goes wrong with float64
  3. Step 2: Represent money as an int64 in minor units
  4. Step 3: Currency decimal places and ISO 4217
  5. Step 4: Parse and output safely: user input and JSON
  6. Step 5: Applying tax rates, discounts and exchange rates: exact computation with math/big and explicit rounding
  7. Step 6: Allocation: not a cent more, not a cent less
  8. Step 7: When to use a decimal library
  9. Step 8: Store it in the database, compute the order total, and check against the payment provider
  10. Step 9: Testing money code
  11. Common pitfalls
  12. Key takeaways
  13. Next

In the previous article, “Payment Pitfalls: Double Charges, Callbacks and Reconciliation”, we dealt with "was the customer charged twice", "can the callback be trusted" and "do the books reconcile". Along the way we mentioned in passing that amounts must always be stored as integers in minor units, never as floating-point numbers. There is a whole body of practice behind that one sentence: what do you do when currencies have different numbers of decimal places? A 5% tax rate leaves a fraction of a cent, so how do you round it? A discount has to be spread over three products, so how do you guarantee the parts add back up to exactly the original discount? This article covers "handling money in Go" from start to finish, and at the end wires it back into the order service's Order.Total.

What this article solves

Money is the data a business system can least afford to get wrong, yet it is also the data most likely to "look fine". Store prices as float64, run a few tests with 19.99 and 100, and everything works; then one day a report total is off by a cent, an order's tax doesn't match the invoice, or three instalments add up to one dollar less than they should, and only then does anyone start digging. What makes this class of bug so troublesome is that it never crashes the program. It quietly leaves a discrepancy on the books, and the later it is found, the harder it is to trace.

This article builds an internal/money package inside example.com/shop and answers, step by step:

  • Why float64 is unsuitable for money, and where the errors come from.
  • How to represent money as "an int64 in minor units plus a currency", and block mixed currencies and overflow when adding, subtracting and multiplying by a quantity.
  • How to handle the different decimal places of each currency (the ISO 4217 exponent), and how to think about the special case of the New Taiwan dollar.
  • How to safely parse and output amounts from user input and JSON.
  • How to compute exactly with math/big when applying tax rates, discounts and exchange rates, and how to choose the rounding mode explicitly.
  • How to allocate an amount without gaining or losing a single cent.
  • When to switch to a decimal library, which database column types to choose, how the order service computes the total and checks it against the payment provider, how to record currency conversions, and how to test money code.

Step 1: See exactly what goes wrong with float64

First run a small program and see for yourself what happens when you do money arithmetic with floating-point numbers:

package main

import "fmt"

func main() {
	// 1. Constants are evaluated at compile time with arbitrary precision, so this is true, which is misleading
	fmt.Println(0.1+0.2 == 0.3)

	// 2. Once the values go into float64 variables, they are binary floating-point numbers at run time
	a, b := 0.1, 0.2
	fmt.Println(a+b == 0.3)
	fmt.Printf("%.17f\n", a+b)

	// 3. An order has a thousand line items of 0.1 each; add them up
	var sum float64
	for i := 0; i < 1000; i++ {
		sum += 0.1
	}
	fmt.Println(sum == 100)
	fmt.Printf("%.15f\n", sum)

	// 4. Rounding that looks fine
	price := 1.005
	fmt.Printf("%.2f\n", price)
	fmt.Printf("%.20f\n", price)

	// 5. The same sum using integer cents
	var cents int64
	for i := 0; i < 1000; i++ {
		cents += 10 // 0.10 = 10 cents
	}
	fmt.Println(cents == 10000, cents)
}

Actual output:

true
false
0.30000000000000004
false
99.999999999998593
1.00
1.00499999999999989342
true 10000

The true on the first line is easy to be misled by. Go evaluates constant expressions at compile time with arbitrary precision; both sides of 0.1+0.2 == 0.3 are "untyped constants", and what is compared are exact rational numbers, so they are equal. But as soon as the values go into float64 variables, they become binary floating-point numbers at run time, the second line immediately becomes false, and a+b is actually 0.30000000000000004.

In plain terms, the reason is this: float64 stores fractions in binary. Just as decimal cannot write one third exactly (0.3333… never ends), binary cannot write one tenth exactly. In binary, 0.1 is 0.0001100110011…, with "0011" repeating forever, and float64 only has 52 bits for the significant digits, so the rest has to be rounded off. What you think is 0.1 is actually "the binary fraction closest to 0.1", off by roughly 10 to the power of minus 17.

You can't see such a tiny difference in a single value, but money by nature gets added up: a thousand amounts of 0.1 sum not to 100 but to 99.999999999998593. If someone later checks "is it paid in full" with sum == 100, or converts it to an integer with int(sum), they get 99. The fourth example is even more insidious: 1.005 is actually stored as 1.00499999999999989342, so "rounding to two places" gives 1.00 rather than the 1.01 you expected. That is not fmt's fault; the number really is a tiny bit smaller than 1.005.

The last part redoes the same sum as integers in "cents": a thousand additions of 10 cents give exactly 10000 cents with no error at all. Within the range of int64, integer addition, subtraction and multiplication are exact, and that is the foundation of the whole approach.

Tip: There is nothing wrong with floating-point numbers as such; they were designed for scientific computing, where measurements already carry error and what matters is relative precision and speed. Money, on the other hand, is "a discrete value defined by people": a cent is a cent, and what you need is exactness, not an approximation.

Step 2: Represent money as an int64 in minor units

The minor unit is a currency's smallest unit of account: for the US dollar it is the cent, and 1 dollar equals 100 cents; the Japanese yen has no smaller unit, so 1 yen is the minor unit. Store an amount as an integer "number of minor units": 19.99 dollars is 1999, and 1,000 yen is 1000.

An integer alone isn't enough, though. The number 1999 doesn't tell you whether it's US dollars, New Taiwan dollars or yen, and adding 1999 US cents to 1999 yen gives a meaningless result. So an amount must always be bound to its currency, forming a type. This is the principle mentioned in article 6, “Layered Architecture and Dependency Injection in Go”: give the domain's concepts their own types, so incorrect usage is stopped at the level of the type or the constructor.

We define Money in internal/money and add a few core operations:

// Package money represents amounts as integers in minor units.
package money

import (
	"encoding/json"
	"errors"
	"fmt"
	"math"
	"math/bits"
	"strconv"
	"strings"
)

var (
	ErrCurrencyMismatch = errors.New("money: currency mismatch")
	ErrUnknownCurrency  = errors.New("money: unknown currency")
	ErrOverflow         = errors.New("money: overflow")
	ErrInvalidAmount    = errors.New("money: invalid amount")
)

// exponents holds the ISO 4217 number of decimal places (minor unit).
// TWD is 2 in ISO 4217, but most payment providers only accept whole dollars; that conversion lives in the integration layer.
var exponents = map[string]int{
	"TWD": 2, "USD": 2, "EUR": 2, "CNY": 2,
	"JPY": 0, "KRW": 0,
	"KWD": 3, "BHD": 3,
}

// Exponent returns the number of decimal places of a currency.
func Exponent(currency string) (int, error) {
	e, ok := exponents[currency]
	if !ok {
		return 0, fmt.Errorf("%w: %q", ErrUnknownCurrency, currency)
	}
	return e, nil
}

// Money is an amount: Amount is in minor units (for example US cents).
type Money struct {
	Amount   int64
	Currency string
}

// New creates an amount and checks the currency.
func New(amount int64, currency string) (Money, error) {
	if _, err := Exponent(currency); err != nil {
		return Money{}, err
	}
	return Money{Amount: amount, Currency: currency}, nil
}

// Add adds two amounts; a currency mismatch or overflow returns an error.
func (m Money) Add(o Money) (Money, error) {
	if m.Currency != o.Currency {
		return Money{}, fmt.Errorf("%w: %s + %s", ErrCurrencyMismatch, m.Currency, o.Currency)
	}
	if (o.Amount > 0 && m.Amount > math.MaxInt64-o.Amount) ||
		(o.Amount < 0 && m.Amount < math.MinInt64-o.Amount) {
		return Money{}, ErrOverflow
	}
	return Money{Amount: m.Amount + o.Amount, Currency: m.Currency}, nil
}

// Sub subtracts; same rules as Add.
func (m Money) Sub(o Money) (Money, error) {
	if o.Amount == math.MinInt64 {
		return Money{}, ErrOverflow
	}
	return m.Add(Money{Amount: -o.Amount, Currency: o.Currency})
}

// MulInt multiplies by an integer (for example a quantity), detecting overflow with math/bits.
func (m Money) MulInt(n int64) (Money, error) {
	if m.Amount == math.MinInt64 || n == math.MinInt64 {
		return Money{}, ErrOverflow
	}
	neg := (m.Amount < 0) != (n < 0)
	hi, lo := bits.Mul64(abs(m.Amount), abs(n))
	if hi != 0 || lo > math.MaxInt64 {
		return Money{}, ErrOverflow
	}
	v := int64(lo)
	if neg {
		v = -v
	}
	return Money{Amount: v, Currency: m.Currency}, nil
}

func abs(v int64) uint64 {
	if v < 0 {
		return uint64(-v)
	}
	return uint64(v)
}

// String formats using the currency's decimal places, e.g. USD 1999 → "19.99".
func (m Money) String() string {
	e, err := Exponent(m.Currency)
	if err != nil {
		return strconv.FormatInt(m.Amount, 10) + " " + m.Currency
	}
	return formatAmount(m.Amount, e) + " " + m.Currency
}

func formatAmount(amount int64, exp int) string {
	s := strconv.FormatUint(abs(amount), 10)
	if exp > 0 {
		if len(s) <= exp {
			s = strings.Repeat("0", exp-len(s)+1) + s
		}
		s = s[:len(s)-exp] + "." + s[len(s)-exp:]
	}
	if amount < 0 {
		s = "-" + s
	}
	return s
}

// Parse converts a user-entered string (e.g. "19.99") into minor units.
// More decimal places than the currency allows are rejected outright, never silently rounded.
func Parse(s, currency string) (Money, error) {
	exp, err := Exponent(currency)
	if err != nil {
		return Money{}, err
	}
	bad := fmt.Errorf("%w: %q", ErrInvalidAmount, s)
	neg := strings.HasPrefix(s, "-")
	s = strings.TrimPrefix(s, "-")
	intPart, frac, hasDot := strings.Cut(s, ".")
	if intPart == "" || (hasDot && frac == "") || len(frac) > exp {
		return Money{}, bad
	}
	digits := intPart + frac + strings.Repeat("0", exp-len(frac))
	for _, c := range digits {
		if c < '0' || c > '9' {
			return Money{}, bad // rejects "1e3", "+5", "1,000" and whitespace
		}
	}
	v, err := strconv.ParseInt(digits, 10, 64)
	if err != nil {
		return Money{}, ErrOverflow
	}
	if neg {
		v = -v
	}
	return Money{Amount: v, Currency: currency}, nil
}

type wire struct {
	Amount   string `json:"amount"`
	Currency string `json:"currency"`
}

// MarshalJSON outputs {"amount":"19.99","currency":"USD"}; the amount is always a string.
func (m Money) MarshalJSON() ([]byte, error) {
	e, err := Exponent(m.Currency)
	if err != nil {
		return nil, err
	}
	return json.Marshal(wire{Amount: formatAmount(m.Amount, e), Currency: m.Currency})
}

// UnmarshalJSON only accepts string amounts; {"amount":19.99} fails with a type mismatch.
func (m *Money) UnmarshalJSON(b []byte) error {
	var w wire
	if err := json.Unmarshal(b, &w); err != nil {
		return err
	}
	v, err := Parse(w.Amount, w.Currency)
	if err != nil {
		return err
	}
	*m = v
	return nil
}

A few design points:

  • The fields are exported, but every operation goes through a method. Money{Amount: 1999, Currency: "USD"} is convenient in tests and when scanning from the database; the operations that can actually go wrong (add, subtract, multiply) always go through Add, Sub and MulInt, which check the currency and overflow.
  • A currency mismatch returns an error rather than converting automatically. Converting needs an exchange rate, a point in time and a rounding mode, and must never happen silently inside Add. To convert, call Convert from Step 5 explicitly.
  • Check for overflow. The upper limit of int64 is about 9.22 × 10¹⁸, which in cents is roughly nine hundred trillion dollars; ordinary orders never get near it. But amounts are often multiplied by quantities, accumulated into reports, or stuffed with huge values by malicious input. Integer overflow in Go doesn't panic; it silently wraps around to a negative number, and an order for "minus nine hundred trillion" is worse than a crash. Add checks explicit upper and lower bounds; MulInt uses math/bits.Mul64 to compute the 128-bit product, and a non-zero high word means the result is out of range.
  • Errors are wrapped sentinels. Following article 2, “Error Handling in Go: Wrapping, Sentinels and Custom Types”, callers can check with errors.Is(err, money.ErrCurrencyMismatch), while the error message carries the actual currencies to make debugging easier.
User input "19.99" USD JSON request Amount is a string Database BIGINT + currency money.Money Amount int64 = 1999 Currency = "USD" Add/Sub: same currency only MulInt: quantity, overflow MulRat: ratio + rounding Format/JSON "19.99" Allocate Never loses a cent Errors: currency mismatch, overflow, too many digits Always returned as an error, never silently corrected Every way in and out becomes Money first

Figure: User input, JSON and database columns all become Money on the way in; add, subtract, multiply, ratios and allocation all happen inside the type, any failure returns an error, and the value is formatted as a string on the way out.

Tip: Sub blocks math.MinInt64 first because it has no positive counterpart: in two's complement, -math.MinInt64 is still itself. Boundary values like this are what money code most often fails to test; the tests in Step 9 cover them specifically.

Step 3: Currency decimal places and ISO 4217

"The minor unit is 1/100" only holds for some currencies. The international standard ISO 4217 defines a code for every currency (e.g. USD, JPY) and its number of decimal places (the exponent, also often called the minor unit). Common ones:

CurrencyCodeISO 4217 decimal placesMinor units per major unitNotes
US dollarUSD2100The most common case
EuroEUR2100
RenminbiCNY2100
New Taiwan dollarTWD2100The standard says 2, but in practice prices are usually in whole dollars; see below
Japanese yenJPY01No decimals
South Korean wonKRW01No decimals
Kuwaiti dinarKWD31000Three decimal places
Bahraini dinarBHD31000Three decimal places

Money itself only stores an integer and a currency; "how many decimal places this integer represents" is looked up by Exponent. So Money{1999, "USD"} is 19.99 US dollars, Money{1999, "JPY"} is 1,999 yen, and Money{1999, "KWD"} is 1.999 dinars. This is also why an order must always have a currency column: without the currency, the integer cannot be interpreted.

The New Taiwan dollar needs a special note. ISO 4217 gives TWD two decimal places, so by the standard there are subunits; but everyday transactions and cash use whole dollars almost exclusively, and many payment providers' APIs require TWD amounts to be whole dollars with no decimals. The same situation exists for other currencies: the standard number of decimal places does not necessarily match the rules of a given payment provider or the practice of a given country.

There are two common ways to handle this gap:

  1. Follow ISO 4217 internally and convert in the integration layer. Inside the system, TWD is always stored with 2 decimal places (that is, in cents), so an Order.Total of 80000 means 800.00 dollars; before sending it to a provider that requires whole dollars, the payment service's integration layer divides by 100 and checks that it divides evenly, rejecting it otherwise rather than rounding silently. This is the approach this article's code takes, and it keeps the whole series consistent with "Total is an int64 in cents".
  2. Use the business's number of decimal places directly inside the system. If the whole system only sells in New Taiwan dollars and will certainly always price in whole dollars, you can also set TWD's decimal places to 0. The benefit is one fewer conversion; the cost is that if you ever have to accept a currency with decimals, or handle the fractions produced by proportional calculations, you'll have to go back and change the data.

Whichever you choose, the key is that the whole system has exactly one interpretation, and there is exactly one conversion point to the outside. Keep the decimal-places table in internal/money, and document which version and which convention it follows.

Tip: Treat the specification of the payment provider you integrate with as authoritative for decimal places. For the same currency, different payment providers may require different formats (integer minor units, a string with a decimal point, or even whole major units only). Read each provider's API documentation, and write the conversion as a tested function rather than scattering it around.

Step 4: Parse and output safely: user input and JSON

Amounts usually enter the system through a form the user fills in, or through API JSON. Neither should pass through float64. The Parse above splits the string directly into its integer part and fractional part, pads it with zeros to the currency's number of places, and converts it to an integer with strconv.ParseInt, with no floating point anywhere:

  • "19.9" parsed as USD has its fraction padded to two places, "90", giving 1990 cents.
  • "19.999" parsed as USD has three decimal places, more than the dollar's two, and is rejected outright. Don't "round it for the user": the extra digits might mean the user mistyped or the front end miscalculated, and silently correcting it pushes the error out to reconciliation time.
  • "1e3", "+5", "1,000" and leading or trailing whitespace are all stopped by the character-by-character check. To support thousands separators or full-width digits, convert them explicitly in the input layer before calling Parse, and keep Parse strict.
  • If the number is too large for int64, ParseInt returns an error, which we turn into ErrOverflow.

The JSON problem is subtler. The JSON specification itself doesn't limit numeric precision, but the vast majority of implementations (including JavaScript in the browser) parse JSON numbers into double-precision floats. In other words, even if your Go program uses integers, as soon as the API is written as {"amount": 19.99}, the other side's program has most likely already turned it into a float. On top of that, JavaScript's Number can only represent integers exactly up to 2⁵³, a smaller range than int64, so very large integers sent to the front end also lose precision.

So amounts in an API should be strings, sent together with the currency:

{"amount": "19.99", "currency": "USD"}

We implement MarshalJSON and UnmarshalJSON on Money: on output it formats the amount as a string using the decimal places; on input it requires amount to be a string, so {"amount": 19.99} fails immediately with a type mismatch, and then hands the value to Parse for the same strict checks as the form.

Another common API design passes the minor-unit integer as a string, for example {"amount_minor": "1999", "currency": "USD"}, a format many payment providers use. Either works; what matters is being consistent within one API and documenting clearly what unit amount is in.

Tip: String() is only for logs and debugging. The format of amounts shown to users (currency symbol, thousands separator, decimal mark) depends on the locale, for example "NT$1,234" or "1.234,56 €", and should be handled by the front end or a dedicated localisation package. Don't store display strings in the database or use them for calculations.

Step 5: Applying tax rates, discounts and exchange rates: exact computation with math/big and explicit rounding

Adding, subtracting and multiplying by an integer quantity are all exact; the trouble starts when you multiply by a "ratio": 5% sales tax, 15% off, an exchange rate of 31.255. These ratios are themselves fractional, the result is often not a whole number of minor units, and it has to be rounded. Two things need to be done right here:

  1. The ratio itself must be exact. Don't write float64(amount) * 0.05; that takes you straight back to Step 1. Use math/big.Rat to build the exact fraction 5/100 from the string "0.05", or represent ratios as integers (for example in basis points of one ten-thousandth, where 500 means 5%).
  2. The rounding mode must be chosen explicitly. Different situations have different rules, and you can't let the programming language or a library decide for you.

Common rounding modes:

Rounding modeName in code2.5 →3.5 →-2.5 →Common uses
Round half up (half away from zero)HalfUp34-3Ordinary receipts and tax calculations; required by many regulations
Banker's rounding (half to even)HalfEven24-2Large volumes of accrued interest, currency conversion, statistics; positive and negative errors cancel out
Round down (truncate towards zero)Down23-2"Pay out at most this much" situations, such as reward points and discount caps
The same "exactly half" under three rounding modes -3 -2 -1 0 1 2 3 2.5 -2.5 Mode 2.5 3.5 -2.5 Common uses Half up: HalfUp 3 4 -3 Receipts, tax (per regulations) Banker's: HalfEven 2 4 -2 Large totals, interest, statistics Round down: Down 2 3 -2 Discount caps, never overpay The three only diverge at "exactly half": 2.6 always becomes 3 and 2.4 always 2 (except Down, where 2.6 becomes 2)

Figure: The three modes only diverge at "exactly half"; for ordinary values such as 2.6 and 2.4 they give the same result (except round down).

Why is banker's rounding needed? Round half up always rounds up at "exactly half", so if you process a large number of calculations that land exactly on half every day, the overall result is systematically too high. Banker's rounding sends half of those cases up and half down (to the even number), so over time the bias averages out to almost zero. But it is unintuitive: if the tax on a receipt uses banker's rounding, it may differ from what the customer works out on a calculator. So the principle is: follow the regulations, the contract or the payment provider's specification, and write the choice into the code and the documentation, rather than "whatever is convenient".

MulRat below multiplies an amount by a big.Rat: it first uses integer division to get the quotient truncated towards zero and the remainder, then decides from the rounding mode whether to round up. Convert builds on it to handle currency conversion, recording the exchange-rate string and the rounding mode together (used in Step 8). This file also contains the allocation from Step 6:

package money

import (
	"errors"
	"fmt"
	"math"
	"math/big"
	"sort"
)

// Rounding is a rounding mode.
type Rounding int

const (
	HalfUp   Rounding = iota // round half up: 0.5 away from zero
	HalfEven                 // banker's rounding: 0.5 to even
	Down                     // round down: truncate towards zero
)

// MulRat computes m × r (r is an exact fraction, e.g. "0.05" or "1/3"), rounded to the minor unit by mode.
func (m Money) MulRat(r *big.Rat, mode Rounding) (Money, error) {
	n := new(big.Int).Mul(big.NewInt(m.Amount), r.Num())
	q, rem := new(big.Int).QuoRem(n, r.Denom(), new(big.Int)) // q is truncated towards zero
	if rem.Sign() != 0 && mode != Down {
		twice := new(big.Int).Abs(rem)
		twice.Lsh(twice, 1) // compare 2|remainder| with the denominator to see whether it is over half
		c := twice.Cmp(r.Denom())
		if c > 0 || (c == 0 && (mode == HalfUp || q.Bit(0) == 1)) {
			q.Add(q, big.NewInt(int64(n.Sign()))) // step one unit away from zero
		}
	}
	if !q.IsInt64() {
		return Money{}, ErrOverflow
	}
	return Money{Amount: q.Int64(), Currency: m.Currency}, nil
}

// Rate turns strings such as "0.05" or "31.25" into exact fractions; never convert from float64.
func Rate(s string) (*big.Rat, error) {
	r, ok := new(big.Rat).SetString(s)
	if !ok {
		return nil, fmt.Errorf("money: invalid rate %q", s)
	}
	return r, nil
}

// Allocate splits m in proportion to weights using the largest remainder method: the parts always sum to m.
func (m Money) Allocate(weights []int64) ([]Money, error) {
	if m.Amount == math.MinInt64 {
		return nil, ErrOverflow
	}
	total := new(big.Int)
	for _, w := range weights {
		if w < 0 {
			return nil, errors.New("money: negative weight")
		}
		total.Add(total, big.NewInt(w))
	}
	if total.Sign() == 0 {
		return nil, errors.New("money: weights sum to zero")
	}
	sign := int64(1)
	amt := new(big.Int).SetInt64(m.Amount)
	if amt.Sign() < 0 { // negative amounts (e.g. refunds): allocate the absolute value, then restore the sign
		sign = -1
		amt.Neg(amt)
	}
	out := make([]Money, len(weights))
	rems := make([]*big.Int, len(weights))
	left := new(big.Int).Set(amt)
	for i, w := range weights {
		q, r := new(big.Int).QuoRem(new(big.Int).Mul(amt, big.NewInt(w)), total, new(big.Int))
		out[i] = Money{Amount: q.Int64(), Currency: m.Currency}
		rems[i] = r
		left.Sub(left, q)
	}
	// Hand out the leftover (always fewer units than parts) one unit at a time to the largest remainders; ties go to the earlier part
	order := make([]int, len(weights))
	for i := range order {
		order[i] = i
	}
	sort.SliceStable(order, func(a, b int) bool { return rems[order[a]].Cmp(rems[order[b]]) > 0 })
	for k := int64(0); k < left.Int64(); k++ {
		out[order[k]].Amount++
	}
	for i := range out {
		out[i].Amount *= sign
	}
	return out, nil
}

// Split divides into n equal parts, e.g. 100 into 3 → 34, 33, 33.
func (m Money) Split(n int) ([]Money, error) {
	if n <= 0 {
		return nil, errors.New("money: split into non-positive parts")
	}
	w := make([]int64, n)
	for i := range w {
		w[i] = 1
	}
	return m.Allocate(w)
}

// Conversion records which rate a conversion used and how it was rounded, so the books can be reconciled later.
type Conversion struct {
	From     Money
	To       Money
	Rate     string // kept verbatim, e.g. "31.2500": 1 unit of the From currency = Rate units of the To currency
	Rounding Rounding
}

// Convert converts using a rate quoted in major units, and handles currencies with different decimal places.
func Convert(from Money, to, rate string, mode Rounding) (Conversion, error) {
	r, err := Rate(rate)
	if err != nil {
		return Conversion{}, err
	}
	ef, err := Exponent(from.Currency)
	if err != nil {
		return Conversion{}, err
	}
	et, err := Exponent(to)
	if err != nil {
		return Conversion{}, err
	}
	// minor units of from × rate × 10^(et-ef) = minor units of to
	scale := new(big.Rat).SetInt(new(big.Int).Exp(big.NewInt(10), big.NewInt(int64(abs(int64(et-ef)))), nil))
	if et < ef {
		scale.Inv(scale)
	}
	out, err := Money{Amount: from.Amount, Currency: to}.MulRat(new(big.Rat).Mul(r, scale), mode)
	if err != nil {
		return Conversion{}, err
	}
	return Conversion{From: from, To: out, Rate: rate, Rounding: mode}, nil
}

The decision logic in MulRat is worth reading carefully: after dividing the product by the denominator, if twice the remainder is greater than the denominator, the fractional part is more than half and must round up; if it is exactly equal to the denominator, it is "exactly half": HalfUp rounds up, and HalfEven only rounds up when the quotient is odd (so that it becomes even). The direction of rounding follows the sign of the product, so negative numbers are handled symmetrically: -2.5 becomes -3 under HalfUp, not -2.

The intermediate calculation uses big.Int rather than int64 because "amount × the ratio's numerator" can easily exceed int64: multiply a large amount by a ratio whose denominator is 10000 and the intermediate value gains four extra zeros. Do everything with big.Int, and finally use IsInt64 to confirm the result fits back into an int64.

When Convert converts currencies, it also has to account for differing decimal places: exchange rates are usually quoted in major units (1 US dollar = 31.255 New Taiwan dollars), but we store minor units. Converting from USD (2 places) to JPY (0 places) needs an extra factor of 10⁻²; converting from JPY to KWD (3 places) needs a factor of 10³. Folding this factor into the fraction and computing it all at once means rounding only once, which is one error fewer than "convert to major units, round, then convert back to minor units".

Tip: Wherever there is rounding, you have to decide at which layer to round, and how many times. For example, should tax be "computed and rounded per line" or "computed once on the order subtotal and then rounded"? The two can differ by a cent or two. This is a business rule: confirm it with finance or the regulations, then write it as one function that every place calls.

Step 6: Allocation: not a cent more, not a cent less

Allocation is the part of money handling most often written wrongly. It comes up in many situations: 100 dollars paid in three instalments; a 100-dollar coupon spread across three products with different prices (so that on a return you know how much each product was actually discounted); shipping costs split by weight across several shipments.

The intuitive approach is "work out each share proportionally and round it": 100 ÷ 3 = 33.33…, rounded to 33, and three shares add up to 99, one dollar short. With other numbers it could be one dollar over. As long as each share is rounded on its own, the total is not guaranteed.

One correct approach is the largest remainder method:

  1. Each share first gets the integer part of its proportional amount, that is, the rounded-down result.
  2. Work out the leftover (the original amount minus all the integer parts); the leftover is always smaller than the number of shares.
  3. Hand out the leftover one minor unit at a time, in descending order of the "remainder that was cut off"; when remainders are equal, use a fixed rule (for example, earlier shares first) so the result is reproducible.
Split 100 dollars among 3 people Ideal share 33.33… each Round 1: everyone first takes the integer part, 33; 99 in all, 1 dollar left over A: 33 Remainder 0.333… B: 33 Remainder 0.333… C: 33 Remainder 0.333… Round 2: the leftover goes out one unit each, largest remainder first; on a tie, whoever is listed first gets it A: 34 Gets the leftover B: 33 C: 33 34 + 33 + 33 = 100: the total always equals the original amount Rounding each share on its own gives 33 + 33 + 33 = 99, one dollar short

Figure: Everyone first gets 33 dollars, and the remaining 1 dollar goes to the person with the largest remainder; when all three remainders are equal, the one listed first gets it, and the total always equals the original amount.

Allocate in calc.go above is exactly this algorithm: weights can be any non-negative integers (line subtotals, weights, item counts), and intermediate values use big.Int to avoid overflow; a negative amount (for example a refund) is allocated as its absolute value and then has its sign restored, keeping positive and negative symmetric. Split(n) is the special case where "all weights are 1": Money{100, "TWD"}.Split(3) gives 34, 33, 33.

An example of allocating a discount: an order has three lines with subtotals of 300, 500 and 100 dollars (30000, 50000 and 10000 in cents), and the whole order gets 100 dollars off. Allocating 10000 cents with the subtotals as weights: the ideal values for the three lines are 3333.33…, 5555.55… and 1111.11… cents; first each gets its integer part, 3333, 5555 and 1111, which add up to 9999, and the remaining 1 cent goes to the second line, which has the largest remainder (0.55…), giving 3333, 5556 and 1111, totalling exactly 10000. The discounted amounts for each line are 266.67, 444.44 and 88.89 dollars, totalling exactly 800 dollars.

This result must be stored, not recomputed every time it is needed. On a return, "how much was actually paid for this product" must match the original calculation; if the algorithm or the weights are adjusted later, recomputing could give different numbers.

Tip: If your business rules say New Taiwan dollars can only be allocated in whole dollars, call Allocate in units of "dollars" (divide the amount by 100, allocate, then multiply the results back by 100), or use the internal 0-decimal-place approach from Step 3. The algorithm itself doesn't change; only what counts as the "minor unit" does.

Step 7: When to use a decimal library

int64 minor units plus math/big cover most e-commerce and payment needs, but some situations are more natural with a decimal type:

  • You need intermediate precision finer than the currency, such as API billing at 0.0035 dollars per call, or exchange rates and fee rates quoted to six decimal places, where the calculation must not round to cents along the way.
  • Heavy financial calculation (interest, amortisation, portfolios), where formulas have lots of multiplication and division and writing them with minor-unit integers gets verbose.
  • Interoperating with the database's NUMERIC columns or other languages' decimal types.

Common choices in the Go community are github.com/shopspring/decimal and github.com/cockroachdb/apd. The former has a simple API; the latter implements the General Decimal Arithmetic specification, lets you set precision and rounding through a Context, and reports conditions such as inexact results and overflow. Here is a sketch using shopspring/decimal:

// Snippet
import "github.com/shopspring/decimal"

// 12,345 API calls at 0.0035 dollars each; round to cents only at the end
unit := decimal.RequireFromString("0.0035") // build from a string, not NewFromFloat
calls := decimal.NewFromInt(12345)
raw := unit.Mul(calls) // 43.2075; the intermediate value keeps full precision

halfUp := raw.Round(2)   // 43.21: half away from zero
bank := raw.RoundBank(2) // 43.21: half to even (not exactly half here, so the same)
down := raw.Truncate(2)  // 43.2 (i.e. 43.20): truncate towards zero

// Convert back to minor-unit integers before storing: 43.21 → 4321 cents
cents := halfUp.Shift(2).IntPart()
fmt.Println(raw, halfUp, bank, down, cents)

The trade-offs between the two approaches:

Aspectint64 minor units (+ math/big)Decimal library
PrecisionFixed at the currency's minor unitAny number of decimal places
Performance and memoryOrdinary operations are native integers; fastestEvery value has an internal big integer; slower, and allocates memory
DependenciesStandard library onlyOne more third-party dependency
Comparison and hashingCan use == directly and serve as a map keyMust call Equal; 1.0 and 1.00 may have different internal representations
Easy mistakesForgetting to handle the currency's decimal placesStoring without rounding to the currency's places; the default precision of division
Good forOrders, payments, refunds, account balancesIntermediate calculations such as billing rates, interest and exchange rates

A common combination is: store and transmit as minor-unit integers, do complex intermediate calculations with decimal, and convert back to minor units with an explicit rounding mode as soon as the calculation is done. Whichever you use, float64 should never appear on a money path, including "convert to float64 first, then build a decimal", such as decimal.NewFromFloat(0.1): although the library tries its best to recover the value, the input itself is already an approximation. Build from a string or an integer instead.

Step 8: Store it in the database, compute the order total, and check against the payment provider

Database columns. In PostgreSQL there are two good choices for money, and a few to avoid:

Column typeWhat it storesRecommendation
BIGINTAn integer in minor unitsRecommended: maps one-to-one to Go's int64; the simplest
NUMERIC(p, s)Exact decimal, e.g. NUMERIC(19,4)Suitable for amounts or rates that need to be finer than the minor unit
REAL / DOUBLE PRECISION / FLOATBinary floating pointDon't use: the same problem as Step 1
MONEYPostgreSQL's currency typeNot recommended: decimal places and format depend on the database's locale settings, and it carries no currency

Whichever you use, the currency needs its own column, with constraints. The order tables can be designed like this:

CREATE TABLE orders (
    id          TEXT PRIMARY KEY,
    user_id     TEXT        NOT NULL,
    currency    CHAR(3)     NOT NULL CHECK (currency ~ '^[A-Z]{3}$'),
    discount    BIGINT      NOT NULL DEFAULT 0 CHECK (discount >= 0),
    total       BIGINT      NOT NULL CHECK (total >= 0),  -- minor units
    status      TEXT        NOT NULL CHECK (status IN ('pending', 'paid', 'cancelled')),
    created_at  TIMESTAMPTZ NOT NULL DEFAULT now()
);

CREATE TABLE order_items (
    order_id     TEXT   NOT NULL REFERENCES orders(id),
    line_no      INT    NOT NULL,
    sku          TEXT   NOT NULL,
    quantity     BIGINT NOT NULL CHECK (quantity > 0),
    unit_price   BIGINT NOT NULL CHECK (unit_price >= 0),
    line_total   BIGINT NOT NULL,  -- amount after the allocated discount; stored once computed, never recomputed
    PRIMARY KEY (order_id, line_no)
);

-- Conversion records: how much was converted, at which rate, and how it was rounded
CREATE TABLE fx_conversions (
    id            BIGSERIAL PRIMARY KEY,
    order_id      TEXT        NOT NULL REFERENCES orders(id),
    from_amount   BIGINT      NOT NULL,
    from_currency CHAR(3)     NOT NULL,
    to_amount     BIGINT      NOT NULL,
    to_currency   CHAR(3)     NOT NULL,
    rate          NUMERIC(20,10) NOT NULL,
    rounding      TEXT        NOT NULL,
    rate_source   TEXT        NOT NULL,
    rated_at      TIMESTAMPTZ NOT NULL
);

If you are using database/sql from article 7, “database/sql, Transactions and Connection Pools in Go”, a BIGINT can be scanned straight into an int64; a NUMERIC is best scanned into a string and then handed to money.Parse or a decimal library, never scanned into a float64.

The order service computes the total. An order's total must always be computed by the server from the line items; never trust a total sent by the client. The code below combines the tools from earlier: each line's subtotal is computed with MulInt, the discount is allocated in proportion to the subtotals with Allocate, and finally everything is summed into Order.Total. VerifyPaid is the check described in article 25, “Payment Pitfalls: Double Charges, Callbacks and Reconciliation”, for callbacks and reconciliation:

package order

import (
	"errors"
	"fmt"

	"example.com/check/internal/money"
)

type Item struct {
	SKU       string
	Quantity  int64
	UnitPrice int64 // minor units
}

type Order struct {
	ID       string
	UserID   string
	Items    []Item
	Currency string
	Discount int64 // discount on the whole order, in minor units
	Total    int64 // minor units, as used throughout the series
	Status   string
}

// LineTotals computes each line's amount after the discount: the discount is allocated in proportion to the line subtotals, and the sum is guaranteed to equal the subtotal minus the discount.
func (o Order) LineTotals() ([]money.Money, error) {
	subtotals := make([]money.Money, len(o.Items))
	weights := make([]int64, len(o.Items))
	sum := money.Money{Currency: o.Currency}
	for i, it := range o.Items {
		if it.Quantity <= 0 || it.UnitPrice < 0 {
			return nil, fmt.Errorf("order: invalid item %q", it.SKU)
		}
		line, err := money.Money{Amount: it.UnitPrice, Currency: o.Currency}.MulInt(it.Quantity)
		if err != nil {
			return nil, err
		}
		subtotals[i], weights[i] = line, line.Amount
		if sum, err = sum.Add(line); err != nil {
			return nil, err
		}
	}
	if o.Discount < 0 || o.Discount > sum.Amount {
		return nil, errors.New("order: discount out of range")
	}
	if o.Discount == 0 {
		return subtotals, nil
	}
	shares, err := money.Money{Amount: o.Discount, Currency: o.Currency}.Allocate(weights)
	if err != nil {
		return nil, err
	}
	for i := range subtotals {
		if subtotals[i], err = subtotals[i].Sub(shares[i]); err != nil {
			return nil, err
		}
	}
	return subtotals, nil
}

// ComputeTotal computes Total from the line items; call it before writing to the database, and never trust a total sent by the client.
func (o *Order) ComputeTotal() error {
	lines, err := o.LineTotals()
	if err != nil {
		return err
	}
	total := money.Money{Currency: o.Currency}
	for _, l := range lines {
		if total, err = total.Add(l); err != nil {
			return err
		}
	}
	o.Total = total.Amount
	return nil
}

// VerifyPaid compares the amount and currency returned by the payment provider; any difference at all means the order cannot be marked paid.
func (o Order) VerifyPaid(paid money.Money) error {
	if paid.Currency != o.Currency || paid.Amount != o.Total {
		return fmt.Errorf("order %s: amount mismatch: want %d %s, got %d %s",
			o.ID, o.Total, o.Currency, paid.Amount, paid.Currency)
	}
	return nil
}

This code deliberately routes every amount through the money package: multiplying by the quantity checks for overflow, summing checks the currency, and the discount can't exceed the subtotal. The result of LineTotals is stored in order_items.line_total, and ComputeTotal must be called in the same transaction that creates the order, so that orders.total and the line items always agree.

Checking against the payment provider. The amount carried by a callback or a reconciliation file must first be converted back to the system's internal unit in the payment service's integration layer, according to the specification (for example, multiplying whole dollars by 100), and then handed to VerifyPaid to compare both the amount and the currency. If anything differs, the order must not be marked paid: the user may have changed the amount when paying, the integration layer's conversion may be wrong, or the callback may be forged. The correct handling is to leave the order as it is, write a log entry, raise an alert, and send it into a manual or automated reconciliation process.

order service Total 80000 TWD payment service Converts per spec Payment provider Takes 800 (whole dollars) Callback or reconciliation Returns 800 Compare amounts Back to 80000 first Match Order marked paid Mismatch Status unchanged, alert FX record Rate + rounding Unit conversion only happens in payment's integration layer; everywhere else uses the same minor units and currency

Figure: Unit conversion only happens in the payment service's integration layer; callbacks and reconciliation convert back to the same unit for comparison, and the order is marked paid only if they match. Currency conversions separately record the rate and the rounding mode.

Record every currency conversion. When the order currency differs from the payment currency (for example, products priced in US dollars, paid for by the customer in New Taiwan dollars), the conversion result must be stored together with "which rate was used, where the rate came from, what time the rate was for, and which rounding mode was applied". That is what the fx_conversions table and the Conversion struct above are for. Exchange rates change by the second; if any one of these is missing afterwards, you cannot reproduce the calculation, and you can't explain a few cents' difference at reconciliation time. Keep the rate verbatim as a string or NUMERIC; don't convert it to a float.

Tip: Refunds must be based on "the amount and currency actually received at the time", not reconverted at today's rate. Partial refunds likewise use the stored, allocated line_total, which guarantees that refunding everything adds up to exactly the total originally received.

Step 9: Testing money code

Money bugs often only show up at specific values, so the tests have to go looking for the boundaries deliberately. Using the table-driven style from article 8, “Testing in Go: Table-Driven Tests, httptest and Integration Tests”, list normal values, boundary values and inputs that should be rejected side by side:

package money

import (
	"encoding/json"
	"errors"
	"math"
	"math/rand"
	"testing"
)

func TestParse(t *testing.T) {
	tests := []struct {
		in, cur string
		want    int64
		wantErr bool
	}{
		{"19.99", "USD", 1999, false},
		{"19.9", "USD", 1990, false},
		{"0.05", "USD", 5, false},
		{"-3.50", "USD", -350, false},
		{"1000", "JPY", 1000, false},
		{"1.234", "KWD", 1234, false},
		{"19.999", "USD", 0, true}, // too many digits: reject, never silently round
		{"1.5", "JPY", 0, true},
		{"1e3", "USD", 0, true},
		{"1,000", "USD", 0, true},
		{" 5", "USD", 0, true},
		{"5.", "USD", 0, true},
		{"", "USD", 0, true},
		{"99999999999999999999", "USD", 0, true}, // exceeds int64
		{"1", "XXX", 0, true},
	}
	for _, tt := range tests {
		got, err := Parse(tt.in, tt.cur)
		if (err != nil) != tt.wantErr {
			t.Errorf("Parse(%q,%s) err = %v, wantErr %v", tt.in, tt.cur, err, tt.wantErr)
			continue
		}
		if err == nil && got.Amount != tt.want {
			t.Errorf("Parse(%q,%s) = %d, want %d", tt.in, tt.cur, got.Amount, tt.want)
		}
	}
}

func TestAddRejectsMixedCurrencyAndOverflow(t *testing.T) {
	usd, twd := Money{100, "USD"}, Money{100, "TWD"}
	if _, err := usd.Add(twd); !errors.Is(err, ErrCurrencyMismatch) {
		t.Errorf("want ErrCurrencyMismatch, got %v", err)
	}
	if _, err := (Money{math.MaxInt64, "USD"}).Add(Money{1, "USD"}); !errors.Is(err, ErrOverflow) {
		t.Errorf("want ErrOverflow, got %v", err)
	}
	if _, err := (Money{math.MaxInt64/2 + 1, "USD"}).MulInt(2); !errors.Is(err, ErrOverflow) {
		t.Errorf("want ErrOverflow, got %v", err)
	}
}

func TestMulRatRounding(t *testing.T) {
	half, _ := Rate("0.5")
	tests := []struct {
		amount int64
		mode   Rounding
		want   int64
	}{
		{5, HalfUp, 3}, {5, HalfEven, 2}, {5, Down, 2}, // 2.5
		{7, HalfUp, 4}, {7, HalfEven, 4}, {7, Down, 3}, // 3.5
		{-5, HalfUp, -3}, {-5, HalfEven, -2}, {-5, Down, -2}, // -2.5
	}
	for _, tt := range tests {
		got, err := Money{tt.amount, "USD"}.MulRat(half, tt.mode)
		if err != nil || got.Amount != tt.want {
			t.Errorf("%d×0.5 mode %d = %d (%v), want %d", tt.amount, tt.mode, got.Amount, err, tt.want)
		}
	}
}

func TestJSONUsesStrings(t *testing.T) {
	b, _ := json.Marshal(Money{1999, "USD"})
	if string(b) != `{"amount":"19.99","currency":"USD"}` {
		t.Errorf("got %s", b)
	}
	var m Money
	if err := json.Unmarshal([]byte(`{"amount":19.99,"currency":"USD"}`), &m); err == nil {
		t.Error("number amount should be rejected")
	}
	if err := json.Unmarshal([]byte(`{"amount":"-0.05","currency":"USD"}`), &m); err != nil || m.Amount != -5 {
		t.Errorf("got %v, %v", m, err)
	}
}

func TestConvertRecordsRate(t *testing.T) {
	// 10.00 USD at a rate of 31.255, HalfUp → 312.55 TWD (TWD has 2 decimal places per ISO)
	c, err := Convert(Money{1000, "USD"}, "TWD", "31.255", HalfUp)
	if err != nil || c.To.Amount != 31255 || c.Rate != "31.255" {
		t.Errorf("got %+v, %v", c, err)
	}
	// 1,000 JPY → USD at a rate of 0.0067 → 6.70 USD
	c, err = Convert(Money{1000, "JPY"}, "USD", "0.0067", HalfEven)
	if err != nil || c.To.Amount != 670 {
		t.Errorf("got %+v, %v", c, err)
	}
}

func TestSplit(t *testing.T) {
	parts, _ := Money{100, "TWD"}.Split(3)
	want := []int64{34, 33, 33}
	for i := range want {
		if parts[i].Amount != want[i] {
			t.Fatalf("Split(100,3) = %v, want %v", parts, want)
		}
	}
}

// Property-style test: with random amounts and weights, the allocated parts always sum to the original amount, and each part is within 1 of its ideal value.
func TestAllocateSumsToTotal(t *testing.T) {
	rng := rand.New(rand.NewSource(1))
	for i := 0; i < 10000; i++ {
		amount := rng.Int63n(2_000_000) - 1_000_000
		weights := make([]int64, 1+rng.Intn(8))
		var wsum int64
		for j := range weights {
			weights[j] = rng.Int63n(1000)
			wsum += weights[j]
		}
		if wsum == 0 {
			continue
		}
		parts, err := Money{amount, "USD"}.Allocate(weights)
		if err != nil {
			t.Fatal(err)
		}
		var sum int64
		for j, p := range parts {
			sum += p.Amount
			ideal := float64(amount) * float64(weights[j]) / float64(wsum) // only used in the test to measure distance
			if d := float64(p.Amount) - ideal; d <= -1 || d >= 1 {
				t.Fatalf("part %d = %d, ideal %.3f", j, p.Amount, ideal)
			}
		}
		if sum != amount {
			t.Fatalf("Allocate(%d, %v) sums to %d", amount, weights, sum)
		}
	}
}

These tests cover several key areas:

  • Parsing: different currencies' decimal places, negative numbers, too many digits, scientific notation, thousands separators, whitespace, numbers beyond int64, and unknown currencies. Every "should fail" case is an input you really will receive in production.
  • Arithmetic: mixing currencies must fail; addition and multiplication near math.MaxInt64 must report overflow rather than wrapping to a negative number.
  • Rounding: every rounding mode is tested at "exactly half" on a positive number, on another positive number of different parity, and on a negative number. Testing only values like 2.6 that aren't at half passes for all three modes, which is as good as not testing.
  • JSON: output is a string; numeric amounts must be rejected.
  • Currency conversion: converting between two currencies with different decimal places must produce the correct result and the correct rate record.
  • Properties of allocation: the last test doesn't list fixed answers; instead it uses a fixed seed to generate ten thousand random amounts and weights, and checks two properties that must always hold: the parts sum to the original amount, and each part differs from its ideal proportion by less than one minor unit. This kind of "property test" finds combinations people wouldn't think of, such as zero weights, negative amounts, or a single part. The fixed seed makes failures reproducible; Go's built-in fuzzing (go test -fuzz) can be used for the same purpose.

Using float64 in the test to compute the "ideal value" is fine, because it is only used to judge whether the distance is less than 1, and never flows into production code.

Tip: Beyond unit tests, reconciliation itself is the money system's "test" in production. Every day, compare the totals of orders, payment provider settlements and refunds; if the difference isn't zero, someone needs to look at it.

Common pitfalls

  • Using float64 at any step. That includes parsing from JSON, handling user input with strconv.ParseFloat, DOUBLE PRECISION database columns, or decimal.NewFromFloat. Pass through it once and the precision never comes back.
  • Thinking 0.1+0.2 == 0.3 being true means there's no problem. Go's untyped constants are computed exactly at compile time, and only become floating point once they go into variables; experimenting with constants leads to the wrong conclusion.
  • Amounts without a currency. Integer-only amounts break the day a second currency appears, and the data can't be repaired.
  • The system doesn't agree on decimal places. For example, the order service treats TWD as 2 places and the payment service as 0, so amounts are off by a factor of a hundred. There must be exactly one conversion point, and it must be tested.
  • Unchecked integer overflow. Go doesn't panic; it silently becomes a negative number. Watch "amount × quantity" and "amount × the ratio's numerator" in particular.
  • Relying on default rounding. Different languages, libraries and databases don't necessarily share the same default rounding; when the same calculation gives different results in the front end, the back end and a report, this is often why.
  • Rounding each share and then summing. Instalments, allocations and split orders all need the largest remainder method or something similar, to keep the total unchanged.
  • Recomputing amounts that have already been settled. Allocation results, conversion results and tax amounts must be stored at the time; if the algorithm or the rate changes later, recomputed results won't match.
  • Trusting a total sent by the client. The total is always computed by the server from the line items and the prices at the time.
  • Callbacks that check "success" but not the amount. If a payment succeeded but the amount or currency is wrong, the order can't be marked as paid.

Key takeaways

  • float64 stores fractions in binary, so numbers like 0.1 can't be represented exactly, and summing, comparing and rounding all go wrong; don't use floating point for money.
  • Represent money as an int64 in minor units, bound to its currency in a Money type; only allow adding and subtracting the same currency, and check multiplication and summing for overflow.
  • A currency's decimal places follow ISO 4217: JPY and KRW have 0, USD and EUR have 2, KWD and BHD have 3; TWD is 2 by the standard, but many payment providers only accept whole dollars, so keep the conversion in the integration layer and treat the provider's specification as authoritative.
  • Use strings for amounts in user input and JSON, parse them strictly, and reject too many digits outright; don't put numeric amounts in JSON.
  • When applying tax rates, discounts and exchange rates, represent exact ratios with big.Rat, do intermediate calculations with big.Int, and explicitly choose round half up, banker's rounding or round down.
  • Allocate with the largest remainder method, so the total always equals the original amount, and store the results.
  • Use a decimal library when you need finer intermediate precision, but still return to minor-unit integers for storage and transmission.
  • In the database use BIGINT or NUMERIC, plus a currency column and constraints; don't use FLOAT, REAL or MONEY.
  • The server computes the order total; callbacks and reconciliation compare both amount and currency; currency conversions record the rate, its source, its time and the rounding mode.
  • Tests should cover boundary values and "exactly half" for every rounding mode, and use property tests to check that allocations sum correctly.

Next

At this point, the system can calculate money, collect it and reconcile it correctly. The next article, “Microservice Security: Authentication, Authorisation, Secrets and Supply Chain”, is about protecting it: how services authenticate and authorise each other, how to manage secrets, and supply-chain security for dependencies and container images.