All resources
Data Architecture9 min read

Represent money with decimal rules, not floating point

How to store amounts, currencies, rounding, tax, and exchange rates so billing calculations remain explainable.

A practical PingFlow guide for developers working at the boundary between systems.

At a glance

Key takeaways

  • Start with the boundary
  • Model the system before choosing a tool
  • Design for failure, misuse, and change
In this guide

Start with the boundary

Represent money with decimal rules, not floating point is easiest to get right when the boundary is named before the implementation begins. Decide which system owns the decision, which inputs are trusted, what the caller can observe, and what must remain private. That framing prevents a local optimization from quietly becoming an undocumented protocol.

Money is a domain rule with a currency, scale, rounding mode, and source—not merely a number. Binary floating point can represent neither many decimal fractions nor every intermediate calculation exactly. A billing system also needs to explain why a total changed and to reproduce a historical result after rates or tax rules evolve.

Model the system before choosing a tool

Store a minor-unit integer when the currency scale is fixed and well understood, or use a decimal type with explicit precision. Keep currency code, amount, unit price, quantity, tax, discount, and rounding decisions separate. Store the rate and rule version used for conversions. Never infer currency from a locale or format a value before calculating.

Write the model down as a small state diagram or table before selecting a library. Identify the durable state, the derived state, and the transitions that may be retried. This makes it easier to compare a managed service with an in-process implementation and to explain why a particular trade-off is acceptable for this workload.

Design for failure, misuse, and change

Rounding each line versus the invoice total can produce different cents, currencies have different minor-unit scales, and a negative discount can create a total below zero. Retries can charge twice if the payment intent or invoice is not idempotent. A refund must refer to the original currency and amount, not a newly converted value.

A resilient design assumes that inputs are incomplete, dependencies are slow, operators make mistakes, and requirements will change. Put limits at the boundary, return errors that a caller can act on, and preserve enough context to distinguish a bad request from an unavailable dependency. Avoid broad fallbacks that make an unsafe state look successful.

Implementation example

Define calculation order and rounding at each boundary. Use a decimal library or integer arithmetic with checked overflow, and reject values with more precision than the currency allows unless the rule explicitly rounds them. Persist a calculation breakdown and the rule or rate identifiers. Send the same idempotency key through checkout, invoice creation, and payment confirmation.

Keep the first implementation narrow enough to review line by line. Make inputs, outputs, authorization context, and failure behavior explicit instead of hiding them behind a convenience helper. The example should be safe to run with synthetic data, emit a correlation identifier, and leave a durable artifact that another engineer can inspect after the request has finished.

text
subtotal = decimal(unit_price) * decimal(quantity)
tax = round(subtotal * tax_rate, currency_scale, ROUND_HALF_UP)
total = subtotal + tax - discount

Verify and troubleshoot

Test half-even and half-up boundaries, negative values, zero-decimal and three-decimal currencies, large quantities, taxes, discounts, refunds, exchange rates, and repeated requests. Compare a reference implementation with the production library. Verify serialized values round-trip without losing scale or currency.

Use a small test matrix that covers the ordinary path, an empty or missing input, a duplicate request, a timeout, a permission failure, and a version mismatch. Assert both the response and the side effects. When a test fails, compare the observed transition with the model rather than adding a retry or widening a timeout without evidence.

Operations and recovery

Monitor reconciliation differences, rounding adjustments, duplicate payment attempts, rate age, and failed refunds. Keep a ledger or immutable transaction record for the amount actually charged. During an incident, stop new charges if calculations are suspect and preserve the input, rule version, and provider response for repair.

Give the operator a bounded recovery action: replay a safe event, rebuild a derived view, rotate a credential, drain a queue, or roll back a compatible revision. Record the owner, retention period, alert threshold, and rollback condition next to the implementation. A runbook is useful only when it can be followed without reconstructing the design from production logs.

A practical decision guide

For a small service, prefer the design with the fewest hidden states that still meets the data architecture requirement. Add a managed dependency when it removes a failure mode you can measure, not simply because it is popular. Keep the interface replaceable by isolating provider-specific code behind a narrow adapter and by testing the behavior your users depend on.

Revisit the decision when traffic shape, data sensitivity, team ownership, or recovery objectives change. A design that is excellent for a single tenant or a low-volume internal tool can be the wrong design for a public multi-tenant path. Record the assumptions so the next change starts with evidence rather than folklore.

An implementation checklist

Before publishing a change related to represent money with decimal rules, not floating point, write down the input contract, authorization context, state transitions, limits, and user-visible errors. Identify the smallest synthetic dataset that demonstrates the normal path and the smallest dataset that demonstrates the dangerous path. Add a correlation ID to the example, make retries deliberate, and decide which artifacts can be retained for support without copying secrets or unnecessary personal data. This checklist is deliberately boring: repeatable release evidence is more valuable than a clever demo.

Use a disposable environment to exercise the implementation with realistic concurrency and a dependency failure. Compare the observed result with the contract, then record the measured latency, resource use, and recovery action. If a managed service or library is involved, pin its version and capture the relevant configuration. Ship behind a reversible change when the behavior is new, and schedule a follow-up review after real traffic reveals assumptions that a test fixture could not.

References and further reading

Use ISO 4217, payment-provider decimal and idempotency documentation, and accounting guidance for rounding and ledger entries. Have finance review the calculation contract; a technically precise formula can still be the wrong business rule.

Prefer primary protocol specifications, vendor security documentation, and measured behavior from a disposable environment. Read the failure and deprecation sections, not only the happy-path quick start. A short reference list attached to the code gives future maintainers a way to distinguish an intentional constraint from an accidental implementation detail.

Keep exploring