All notes
Fintech

0.1 + 0.2 ≠ 0.3: storing money as Decimal and minor units, rounding, and the lost tiyin

Money stored as float drifts by a few cents by month end. How Decimal and minor units work, when HALF_UP and banker's rounding disagree, and how to split fees without losing a cent, with a Django model.

Picture this: your payment service takes a 1.5% fee on every transaction. A customer pays 12,335 UZS, the code computes the fee and sends the rest to the merchant. At month end, accounting reconciles the report against the bank statement and finds a gap of a few tiyin. The amount is trivial, but now someone has to recheck every transaction, because nobody knows where the difference came from.

Almost every gap like that comes from one of three places: money stored as float, rounding done in random places with random rules, and a leftover tiyin lost when an amount is split into parts. Let's go through all three and finish with a working Django model.

Why 0.1 + 0.2 is not 0.3

Open a Python shell:

>>> 0.1 + 0.2
0.30000000000000004
>>> sum([0.1] * 10)
0.9999999999999999
>>> round(2.675, 2)
2.67

This isn't a Python bug. A float is a 64-bit binary number defined by IEEE 754, stored as mantissa × 2^exponent. Just as 1/3 can't be written exactly as a decimal fraction (0.3333...), 0.1 can't be written exactly as a binary fraction: it repeats forever. So what sits in memory is not 0.1 but the nearest binary number to it:

>>> from decimal import Decimal
>>> Decimal(0.1)
Decimal('0.1000000000000000055511151231257827021181583404541015625')

That's also why round(2.675, 2) returns 2.67: the stored value is really 2.67499999..., so it isn't a tie at all.

In physics or graphics this error doesn't matter. With money it does: errors accumulate, == comparisons surprise you, and rounding goes the wrong way. PostgreSQL behaves the same:

SELECT 0.1::float8 + 0.2::float8;    -- 0.30000000000000004
SELECT 0.1::numeric + 0.2::numeric;  -- 0.3

Money is not a measurement, it's a count. Floats were built for measurements; money has to be counted exactly.

Two correct options: Decimal and minor units

There are two common ways to store money exactly.

1. A decimal number (Decimal / NUMERIC). Python's decimal.Decimal stores a number as decimal digits plus a decimal exponent, so Decimal('0.1') is exactly 0.1. PostgreSQL's numeric type is decimal and exact too. In Django that's DecimalField.

2. Minor units: an integer in the smallest unit. Store the amount in tiyin instead of som: 12,335.00 UZS → 1233500 tiyin. Integer addition and subtraction are always exact. In Django that's BigIntegerField (bigint in PostgreSQL). Many payment APIs, Stripe for example, take amounts exactly like this, in the currency's smallest unit.

How many digits the minor unit has is defined by ISO 4217: 2 for UZS and USD (tiyin, cents), 0 for JPY, 3 for KWD. So "multiply by 100" is not right for every currency; the exponent has to come from the currency.

float Decimal / numeric Minor units (bigint)
Exactness Approximate Exact Exact
Fractional part Yes, but binary Any decimal None, integer
Currency precision — Fixed by decimal_places Currency exponent stored separately
Percentages, FX rates Dangerous Convenient Needs a temporary Decimal
Sending in JSON As a number (dangerous) Usually as a string As an integer

Which one to pick depends on the project. For an internal single-currency system, DecimalField(max_digits=18, decimal_places=2) is enough. For a multi-currency system that talks to external payment gateways, I prefer minor units: the amount is always an integer and the currency sits right next to it. Either way, calculations (percentages, rates) are done in Decimal.

How Decimal works: context and precision

The most forgotten part of Decimal is the context. Every arithmetic operation follows the rules of the current context:

>>> from decimal import getcontext
>>> getcontext()
Context(prec=28, rounding=ROUND_HALF_EVEN, Emin=-999999, Emax=999999, capitals=1, clamp=0, flags=[], traps=[InvalidOperation, DivisionByZero, Overflow])

Two things matter here:

  • prec=28 is not the number of digits after the decimal point; it's the total number of significant digits. Decimal(1) / 3 gives 28 digits. That's plenty for money, but it does not mean "two decimals".
  • rounding=ROUND_HALF_EVEN is the default rounding mode, "banker's rounding". More on it below.

To round an amount to a given number of places, use quantize and always pass the mode explicitly:

from decimal import Decimal, ROUND_HALF_UP

amount = Decimal("185.025")
amount.quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)  # Decimal('185.03')

Changing the context globally (getcontext().prec = 10) is a bad idea: it affects all code in the current thread or asyncio task. If you need a temporary change, use localcontext(). You can also turn on a useful guard there, so a stray float fails immediately:

from decimal import Decimal, FloatOperation, localcontext

with localcontext() as ctx:
    ctx.traps[FloatOperation] = True
    Decimal("0.1")   # fine
    Decimal(0.1)     # decimal.FloatOperation

Adding a Decimal and a float raises TypeError regardless of context, which is good: the mistake doesn't hide.

>>> Decimal("0.1") + 0.2
TypeError: unsupported operand type(s) for +: 'decimal.Decimal' and 'float'

Rounding modes: HALF_UP and banker's rounding

There are two main modes, and they only differ on exact ties:

Value ROUND_HALF_UP ROUND_HALF_EVEN (banker's) PostgreSQL round(numeric)
0.5 1 0 1
1.5 2 2 2
2.5 3 2 3
-2.5 -3 -2 -3
  • HALF_UP is what school taught you: .5 goes away from zero. In Python, ROUND_HALF_UP rounds negative ties away from zero too.
  • HALF_EVEN (banker's rounding) sends .5 to the nearest even digit. When you round and sum many values, HALF_UP systematically pushes the total up; HALF_EVEN cancels that bias on average.

Note that Python's built-in round() is also banker's rounding (round(2.5) == 2), while PostgreSQL's round(numeric) rounds away from zero (round(2.5) = 3). If the same calculation is done in Python in one place and in SQL in another, the results can disagree.

The rounding mode isn't a matter of developer taste. It's usually defined by the payment provider's spec, the contract, or the finance team. Your job is to write the rule down in one place and use it everywhere.

Fees: don't lose the tiyin

Back to the opening example. The payment is 12,335.00 UZS = 1,233,500 tiyin, with a 1.5% fee:

>>> Decimal(1233500) * Decimal("0.015")
Decimal('18502.500')

An exact tie. HALF_UP gives 18,503 tiyin, HALF_EVEN gives 18,502. One tiyin, but across thousands of transactions it becomes a visible gap between two systems.

An even more common mistake is rounding the fee and the merchant payout separately:

# WRONG: both parts are rounded independently
fee = round(amount * 0.015, 2)
payout = round(amount * 0.985, 2)
# fee + payout is not always equal to amount

That's float plus double rounding. The right way: compute and round one part, and get the other by subtraction. Then the total always adds up:

from decimal import Decimal, ROUND_HALF_UP


def split_fee(amount_minor: int, rate: Decimal) -> tuple[int, int]:
    """Return fee and merchant share in minor units; they always sum to amount_minor."""
    if not isinstance(rate, Decimal):
        raise TypeError("rate must be a Decimal")
    raw = Decimal(amount_minor) * rate
    fee = int(raw.quantize(Decimal("1"), rounding=ROUND_HALF_UP))
    return fee, amount_minor - fee


fee, payout = split_fee(1_233_500, Decimal("0.015"))
assert fee + payout == 1_233_500   # 18503 + 1214997

Splitting an amount into several parts (say, 100 UZS among three partners) is another classic trap: 33.33 × 3 = 99.99, and a tiyin disappears. The fix is to distribute the remainder (the largest remainder method):

def allocate(total_minor: int, weights: list[int]) -> list[int]:
    """Split total_minor in proportion to weights; the parts always sum to total_minor."""
    if total_minor < 0 or not weights or any(w < 0 for w in weights) or sum(weights) == 0:
        raise ValueError("invalid arguments")
    wsum = sum(weights)
    shares = [total_minor * w // wsum for w in weights]
    remainders = [total_minor * w % wsum for w in weights]
    leftover = total_minor - sum(shares)
    # hand the leftover minor units to the shares with the largest remainders
    order = sorted(range(len(weights)), key=lambda i: remainders[i], reverse=True)
    for i in order[:leftover]:
        shares[i] += 1
    return shares


assert allocate(10_000, [1, 1, 1]) == [3334, 3333, 3333]
assert sum(allocate(1_233_500, [70, 20, 10])) == 1_233_500

// and % are exact on integers and sorted is stable, so the result is deterministic: the same input always produces the same split.

The Django model: amount and currency together

An amount without a currency is just a number. Is "1000" som or dollars? That's why amount and currency are always stored side by side and travel through the code as one value.

from decimal import Decimal

from django.db import models
from django.db.models import F, Q

MINOR_EXPONENT = {"UZS": 2, "USD": 2, "EUR": 2, "JPY": 0, "KWD": 3}


class Currency(models.TextChoices):
    UZS = "UZS", "Uzbek som"
    USD = "USD", "US dollar"
    EUR = "EUR", "Euro"


class Payment(models.Model):
    amount_minor = models.BigIntegerField(help_text="In the smallest unit: tiyin, cents")
    fee_minor = models.BigIntegerField(default=0)
    currency = models.CharField(max_length=3, choices=Currency.choices)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        constraints = [
            models.CheckConstraint(
                condition=Q(amount_minor__gt=0),
                name="payment_amount_positive",
            ),
            models.CheckConstraint(
                condition=Q(fee_minor__gte=0) & Q(fee_minor__lte=F("amount_minor")),
                name="payment_fee_within_amount",
            ),
        ]

    @property
    def amount(self) -> Decimal:
        return Decimal(self.amount_minor).scaleb(-MINOR_EXPONENT[self.currency])

CheckConstraint(condition=...) works from Django 5.1 on (the old check= argument is deprecated). The constraints live in the database: whoever writes the row, whether the admin, a management command or raw SQL, a negative amount or a fee larger than the amount won't get stored.

A small helper converts an incoming amount to minor units. It rejects floats and refuses to silently round an amount with more decimals than the currency allows:

def to_minor(amount: Decimal | str, currency: str) -> int:
    if isinstance(amount, float):
        raise TypeError("float is not accepted, pass Decimal or str")
    scaled = Decimal(amount).scaleb(MINOR_EXPONENT[currency])
    if scaled != scaled.to_integral_value():
        raise ValueError(f"{amount} has too many decimal places for {currency}")
    return int(scaled)


assert to_minor("12335.00", "UZS") == 1_233_500
assert to_minor("1500", "JPY") == 1500

If you go the DecimalField route, the model looks like this, and PostgreSQL gets a numeric(18, 2) column:

class Invoice(models.Model):
    amount = models.DecimalField(max_digits=18, decimal_places=2)
    currency = models.CharField(max_length=3, choices=Currency.choices)

Production pitfalls

Silent rounding on save. If you write Decimal("10.005") into a DecimalField(decimal_places=2), full_clean() rejects it, but a plain save() doesn't run validation. On PostgreSQL the value is rounded to the column's scale, with ties going away from zero: 10.005 → 10.01. Another backend may behave differently. Lesson: quantize yourself before saving.

SELECT 10.005::numeric(12, 2);           -- 10.01
SELECT 12345678901.00::numeric(12, 2);   -- ERROR: numeric field overflow

Floats in ORM expressions. F("amount") * 0.015 raises FieldError in Django: DecimalField and FloatField are mixed and the output type can't be inferred. The right version is F("amount") * Value(Decimal("0.015")).

JSON. json.dumps can't serialize Decimal (TypeError), so the "quick fix" sometimes becomes float(amount), and that's exactly where precision is lost. Django's DjangoJSONEncoder and DRF's DecimalField output Decimal as a string. When reading incoming JSON, use json.loads(body, parse_float=Decimal) or accept the amount as an integer in minor units.

Rounding at every step. Rounding intermediate results accumulates error. Do internal math at full precision and round once at the money boundary: when saving, paying out, or printing a receipt.

Exchange rates. A rate is not money; it needs more digits. Don't store it in a decimal_places=2 column. Give it its own higher-precision field (for example max_digits=20, decimal_places=10) and store when the rate was fetched.

Adding different currencies. Summing amount_minor without checking the currency is a silent bug. Always group aggregates by currency: Payment.objects.values("currency").annotate(total=Sum("amount_minor")).

PostgreSQL's money type. Its output format depends on the lc_monetary setting and it doesn't store a currency. For a multi-currency system, numeric or bigint plus a currency code is far more predictable.

Practical checklist

  • Money is never a float: not in the model, not in calculations, not in JSON.
  • One storage format: BigIntegerField (minor units) or DecimalField; don't mix them across the project.
  • Every amount has a currency code (ISO 4217) next to it; the exponent comes from a table, not a hardcoded 100.
  • Decimal is created only from str or int; turn on the FloatOperation trap in tests.
  • The rounding mode is explicit (quantize(..., rounding=...)) and lives in one function.
  • Fees: round one part and subtract for the other; when splitting, distribute the remainder.
  • CheckConstraints in the database: amount is positive, fee doesn't exceed amount.
  • Test invariants like fee + payout == amount.

Takeaway

Floats weren't made for money: they're approximate, and money is counted exactly. Store amounts as integers in minor units or as Decimal/numeric, keep the currency next to them, and define the rounding rule in one place with an explicit mode. The key invariant is simple: the parts must always add up to the whole, so enforce it in code, in tests and in the database.

// comments

Loading comments...

    // next step

    Let's build something together.

    Message me on Telegram
    aslbek@asldev: ~
    ❯