Nov 23, 20266 min read

How to Store Money in Postgres

Integer minor units, numeric, or the money type: how each one stores currency amounts in Postgres, why floats are out, how to handle currencies with zero or three decimal places, and how to split amounts without losing a cent.

Illustration for How to Store Money in Postgres

Every backend that charges, pays out or tracks balances has to pick a column type for money, and the wrong choice does not fail loudly: totals drift by a cent, a yen amount gets multiplied by a hundred, or a restored dump reads values in the wrong format.

Postgres offers three reasonable-looking options, and only two of them belong in a modern schema.

At a glance

bigint minor units + currencynumeric(p, s)moneydouble precision
ExactYesYesYesNo
Stores the currencySeparate columnSeparate columnNoSeparate column
Fractions of a centNoYesup to the scaleNoApproximate
Size8 bytesVariable, around 8 to 12 bytes for typical amounts8 bytes8 bytes
Depends on locale settingsNoNoYes, lc_monetaryNo
Maps to a Go type without a libraryint64Needs a decimal libraryNeeds parsingfloat64

Why floats are out

double precision is binary floating point, and most decimal fractions have no exact binary representation. In Postgres, 0.1::float8 + 0.2::float8 returns 0.30000000000000004, while the same sum on numeric returns 0.3. The money type documentation says it directly: floating point numbers should not be used to handle money because of rounding errors.

Why the money type is a trap

money looks purpose-built, but it stores a single number with a fractional precision taken from the database's lc_monetary setting, prints it in a locale-dependent format such as $12.34, and has no notion of which currency the amount is in. The documentation warns that dumps may not load correctly into a database with a different lc_monetary, and a backend that handles euros and yen in the same table needs a currency column anyway, at which point money adds nothing.

Integer minor units

The approach most payment APIs use is an integer in the currency's smallest unit plus an ISO 4217 code: 1999 with EUR is €19.99. Minor units differ by currency: JPY has no decimal places, so 1999 JPY is ¥1,999, and KWD and BHD have three, as Stripe's currency reference lists. Formatting and conversion code needs a table of exponents, never a hard-coded division by 100.

bigint holds amounts up to about 92 quadrillion minor units, enough for any single transaction, and maps to int64 in Go and to bigint or string in TypeScript (JSON numbers lose precision above 2^53, so send very large amounts as strings).

When numeric is the right type

numeric is exact decimal arithmetic with a declared precision and scale, so it handles values that are not whole minor units: FX rates (numeric(18, 8)), interest accrued per day, per-unit prices for metered billing such as $0.000125 per request, and tax rates. A common schema uses numeric for those intermediate values and rounds to bigint minor units at the moment money moves, with the rounding rule written down.

Splitting amounts without losing a cent

Dividing €10.00 three ways at two decimal places gives 3.33 three times, which adds up to 9.99. Allocate the remainder explicitly instead:

// Split divides amountMinor into n parts that add up exactly, // giving the leftover minor units to the first parts. Negative amounts, // such as refunds, split the same way and keep their sign. func Split(amountMinor int64, n int) ([]int64, error) { if n <= 0 { return nil, errors.New("n must be positive") } parts := make([]int64, n) base := amountMinor / int64(n) rem := amountMinor % int64(n) // has the sign of amountMinor step := int64(1) if rem < 0 { step, rem = -1, -rem } for i := range parts { parts[i] = base if int64(i) < rem { parts[i] += step } } return parts, nil } // Split(1000, 3) == [334 333 333], Split(-100, 3) == [-34 -33 -33]

The same rule applies to refunds of partial orders, marketplace fee splits and installment plans, where the sum of the parts has to equal the original amount to the minor unit.

Best fit: bigint minor units plus a currency column for balances and transactions, numeric for rates and fractional prices, and neither money nor floats.

Money columns in Encore

Encore

Encore is a backend framework with built-in infrastructure, so the payments schema, the currency rules and the endpoint that records a charge sit together in one service, with the migration as the single place the column types are defined:

Get started
brew install encoredev/tap/encore &&
encore app create
Copy

Run in your terminal to get started locally.

-- payments/migrations/1_create_charges.up.sql CREATE TABLE charges ( id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, customer_id text NOT NULL, amount_minor bigint NOT NULL CHECK (amount_minor > 0), currency char(3) NOT NULL CHECK (currency ~ '^[A-Z]{3}$'), created_at timestamptz NOT NULL DEFAULT now() );
// payments/payments.go package payments import ( "context" "fmt" "encore.dev/beta/errs" "encore.dev/storage/sqldb" ) var db = sqldb.NewDatabase("payments", sqldb.DatabaseConfig{Migrations: "./migrations"}) // exponents lists the minor-unit digits for the currencies this service accepts. var exponents = map[string]int{"EUR": 2, "USD": 2, "GBP": 2, "JPY": 0, "KWD": 3} type ChargeParams struct { CustomerID string `json:"customer_id"` AmountMinor int64 `json:"amount_minor"` Currency string `json:"currency"` } type Charge struct { ID int64 `json:"id"` Display string `json:"display"` } //encore:api private method=POST path=/charges func Record(ctx context.Context, p *ChargeParams) (*Charge, error) { exp, ok := exponents[p.Currency] if !ok { return nil, &errs.Error{Code: errs.InvalidArgument, Message: "unsupported currency"} } if p.AmountMinor <= 0 { return nil, &errs.Error{Code: errs.InvalidArgument, Message: "amount must be positive"} } var id int64 err := db.QueryRow(ctx, ` INSERT INTO charges (customer_id, amount_minor, currency) VALUES ($1, $2, $3) RETURNING id `, p.CustomerID, p.AmountMinor, p.Currency).Scan(&id) if err != nil { return nil, err } return &Charge{ID: id, Display: format(p.AmountMinor, exp, p.Currency)}, nil } func format(minor int64, exp int, currency string) string { if exp == 0 { return fmt.Sprintf("%d %s", minor, currency) } div := int64(1) for i := 0; i < exp; i++ { div *= 10 } return fmt.Sprintf("%d.%0*d %s", minor/div, exp, minor%div, currency) }

The CHECK constraints back up the Go validation, so a bug in another code path still cannot write a negative charge or a lowercase currency code. encore run starts Postgres locally with the migration applied, the databases docs cover the query API, and the API errors docs list the codes returned for bad input. Payment provider keys belong in Encore secrets, which keeps their values out of the repository, and deploys provision the database on RDS or Cloud SQL in your account as described in the AWS infrastructure docs.

An AI coding agent adding a refund or payout table tends to copy this one, so integer minor units and a currency column in the first migration keep it from introducing a float or a money column in the next. Pave Bank built a bank in 9 months with Encore Platform, as its case study describes.

Best fit: payment, billing and ledger services that handle more than one currency and need amounts to add up exactly.

Frequently asked questions

What is the best data type for money in Postgres?

Store amounts as bigint in the currency's minor unit, such as cents, next to a three-letter ISO 4217 currency code. Use numeric with an explicit scale when you need fractions of a minor unit, such as FX rates, interest or per-unit prices.

Should I use the Postgres money type?

No, not for multi-currency backends. The money type stores no currency, its fractional precision and output format depend on the lc_monetary setting, and restoring a dump into a database with a different setting can misread the values.

Why should I not store money as a float?

Binary floating point cannot represent most decimal fractions exactly, so 0.1 + 0.2 becomes 0.30000000000000004 and totals drift over many operations. Integers in minor units or numeric are exact.

How do I store money amounts in an Encore service?

Declare amount_minor bigint and currency char(3) columns in the service's migration, keep amounts as int64 in Go and validate the currency in the endpoint. The schema behaves the same on the local Postgres that encore run starts and on RDS or Cloud SQL in your account.

Deploy to your cloud on AWS and Google Cloud
without managing infrastructure

Encore lets developers and agents define application infrastructure directly in code, then automatically provisions it from local development to production in your AWS or GCP account.

~/orders — claude
Claude Code
Claude Code v2.1.180Opus 5.5~/orders