Skip to content
Tutorials Center
My learning

Topics

Lesson 3 of 40 ยท Getting Started

Representing Money Correctly

Why floats break prices, how to store money as integer minor units, handle JPY and KWD exponents, build a Money class and split amounts without losing cents.

Money is the one kind of number in a shop that must never be "approximately right". A one-cent difference between the cart, the invoice and the payment provider causes failed payments, unhappy accountants and support tickets that are very hard to debug. Nearly all of those bugs come from one mistake: using binary floating-point numbers for prices.

In this lesson you will see exactly why floats fail, learn the standard fix (integers in the currency's smallest unit), handle currencies that do not have two decimals, and build a small Money class that can also split an amount fairly. The Python tutorial covers the exact-decimal tools in decimal and fractions; here we apply them to shopping.

Why floats fail

Computers store float values in binary. Most decimal fractions, including 0.1, have no exact binary form, so tiny errors creep in and accumulate.

Python Float prices drift

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The sum is not exactly 1999.0, and round(2.675, 2) gives 2.67 because the stored value is just below 2.675. If a shop calculates tax or discounts with floats, totals will occasionally be off by a cent, and comparisons such as "does the payment equal the order total?" will fail at random.

Minor units: store integers

The most robust approach is to store money as an integer count of the currency's smallest unit (the minor unit): cents for USD and EUR, pence for GBP. A price of $19.99 becomes 1999. Integer arithmetic is exact, comparisons are reliable and every database and payment API handles it well. Stripe, Adyen and most other providers, for example, take amounts as integers in the minor unit.

Rules of thumb:

  • Store and compute with integers everywhere inside your system.
  • Convert to a formatted string only at the edge, when you display it.
  • Store the currency code (ISO 4217, such as USD) next to every amount. An amount without a currency is meaningless.
  • Do not add or compare amounts in different currencies. Convert first, explicitly.

If you prefer to keep decimals in the database, use a DECIMAL(19, 4) or similar column type, never FLOAT or DOUBLE, and parse values into exact decimals in code. Integers in minor units are simpler and harder to misuse.

Not every currency has two decimals

The number of minor-unit digits is called the exponent, and it differs between currencies. ISO 4217 lists it for each one.

Currency Code Exponent Example
US dollar USD 2 1999 means 19.99
Japanese yen JPY 0 1999 means 1999
Kuwaiti dinar KWD 3 1999 means 1.999

Hard-coding "divide by 100" is a classic bug: a 1,500 yen item would be shown as 15 yen. Keep a table of exponents (or use a library that has one) and always look the exponent up from the currency.

flowchart LR
    A["Input: '19.99' USD"] --> B["Look up exponent<br/>USD = 2"]
    B --> C["Integer: 1999"]
    C --> D["Math with integers"]
    D --> E["Format for display<br/>using the exponent"]

Parse once at the edge, compute with integers, format once on the way out.

A Money class

A small value object keeps the currency and amount together and stops you mixing currencies by accident. This version uses Decimal only for parsing and formatting, and integers for everything else.

Python A Money value object

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Compare the result of price * 100 with the float loop earlier: it is exactly 1999.00 USD. The class refuses to add dollars to euros, which turns a silent bug into an immediate error.

Note: A real project would use a vetted library for this (many languages have one) rather than hand-rolling it. Writing it yourself once teaches you what the library protects you from.

Rounding: pick a rule and apply it in one place

Integer minor units remove representation errors, but division and percentages still create fractions of a cent. Ten percent of 1999 cents is 199.9 cents. You must decide how to round, and the choice is a business and legal rule, not a programming detail.

  • Half up (0.5 rounds up) is what most people expect and what many tax rules require.
  • Half even, also called banker's rounding, reduces bias in large sums. It is Python's default for round() and for Decimal contexts.
  • Whatever you choose, round at defined points, such as per line, and document it. Rounding at different moments gives totals that differ by a cent, which is why tax gets its own lesson.

Allocation: splitting without losing cents

Suppose a 10.00 USD discount applies to an order of three lines worth 20.00, 20.00 and 20.00, or a 1.00 USD fee must be shared across three items. Dividing by three gives 33.33 cents each, and 3 x 33 is only 99. A cent has vanished. The fix is allocation: split by ratios, then hand the leftover cents out one at a time so that the parts always sum exactly to the whole.

Python Splitting 100 cents three ways

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

allocate uses floor division, so no part is ever too big, and then distributes the remainder. Proportional allocation of a discount across lines is exactly what you need when part of an order is refunded or taxed later: each line must carry its own share so that the shares add up to the original discount. The promotions lesson builds on this.

Tip: Add a test that, for random totals and ratios, the allocated parts always sum to the total. Property tests like this catch the off-by-one-cent bugs that example-based tests miss.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why should prices be stored as integers in minor units rather than floats?

    Binary floats cannot represent most decimal fractions exactly. Integers in the smallest currency unit avoid representation errors.
  2. 2. A 1500 JPY item is stored as which integer in minor units?

    JPY has an exponent of 0, so its minor unit is the yen itself. Dividing by 100 would be a bug.
  3. 3. What does allocate(100, [1, 1, 1]) need to guarantee?

    Allocation distributes the leftover units so no money is created or lost. The result here is 34, 33, 33.
  4. 4. Why should an amount always be stored with its currency code?

    1999 could mean dollars, yen or dinars, each with a different exponent. The currency tells you how to interpret and display it.

Summary

  • Binary floats cannot represent most decimal prices exactly; never use them for money.
  • Store money as integers in the currency's minor unit, together with an ISO currency code.
  • Currencies have different exponents (USD 2, JPY 0, KWD 3), so always look the exponent up.
  • A Money value object prevents mixing currencies and keeps rounding in one place.
  • Rounding is a business rule: choose it, document it and apply it at defined points.
  • Use allocation (floor, then distribute the remainder) so split amounts add up exactly.

Next: Product Catalogs and Data Modeling, where you design the data behind your products.