skip to content

A Swift payments screen sums prices stored as Double and shows 0.6000000000000001, and Int(price * 100) turns 19.99 into 1998 cents: what is happening, and how should prices be stored?

level: seniorimportance: should knowfreq 55%

answer

  1. binary fractions, decimal prices
  2. every operation rounds
  3. Int(_:) rounds toward zero
  4. round first, then convert
  5. integer minor units

basics

~20 s

Double stores most decimal prices inexactly and rounds every operation, so sums drift; Int(_:) then truncates 1998.9999999999998 to 1998. Store money as integer minor units such as Int cents, and round once, deliberately, when a rate is applied.

solid answer

~40 s

`Double` is binary floating point: `0.1`, `0.2` and `19.99` are stored as the nearest representable values, and every addition rounds again, so the cart total really is `0.6000000000000001` and `total == 0.6` is `false`. The cent bug adds a second effect: `19.99 * 100` is `1998.9999999999998`, and `Int(_:)` rounds toward zero, giving `1998`. A quick repair is `Int((price * 100).rounded())`, but the real fix is to store money as integer minor units, `priceCents: Int`, taken from the source rather than derived from a `Double`, so sums and comparisons are exact. Rounding then happens once, with a chosen rule, when tax or a discount is applied. `Float` is worse, with about half the precision.

code

swift · 14 lines
swift
let cart = [0.10, 0.20, 0.30]
let total = cart.reduce(0, +)
print(total)                             // 0.6000000000000001
print(total == 0.6)                      // false

let price = 19.99
print(Int(price * 100))                  // 1998: Int(_:) rounds toward zero
print(Int((price * 100).rounded()))      // 1999: round first, then convert

let cartCents = [10, 20, 30]             // store integer minor units
let totalCents = cartCents.reduce(0, +)
print(totalCents, totalCents / 100, totalCents % 100)   // 60 0 60

print((2.5).rounded(), (2.5).rounded(.toNearestOrEven))  // 3.0 2.0

go deeper

for a junior

Remember that 0.1 + 0.2 is not exactly 0.3 as a Double, and that Int(_:) drops the fraction instead of rounding.

for a middle

Explain binary representation error, why each operation rounds, and why rounding before Int(_:) fixes the cent conversion.

for a senior

Diagnose drifting totals in a real money flow and move the model to integer minor units, with one deliberate rounding step for rates.

for a principal

Set the money representation and rounding rule as a shared contract across the app and its backend, so no layer re-derives cents from a Double.

## What the payments screen is showing The cart holds prices as `Double`, Swift's default type for a floating-point literal. A `Double` is a **binary floating-point** number with a 52-bit stored significand (`Double.significandBitCount` is 52). Most decimal fractions, including `0.1`, `0.2` and `19.99`, have no exact binary representation, so each stored price is the nearest representable value, a tiny bit above or below the decimal you wrote. Floating-point arithmetic then **rounds every result** to the nearest representable value. Adding `0.10`, `0.20` and `0.30` accumulates those small errors, and `print` shows `0.6000000000000001`. Nothing is wrong with `print`: the stored total really is not 0.6, which is also why `total == 0.6` is `false`. ## Why Int(price * 100) loses a cent Converting to cents multiplies first: `19.99 * 100` evaluates to `1998.9999999999998`, because `19.99` was stored slightly below 19.99. Then `Int(_:)` converts a floating-point value by **rounding toward zero**, so the fraction is dropped and the result is `1998`, not `1999`. Two separate effects combine: - the representation error makes the product fall just short of the whole number; - the truncating conversion turns "just short" into a whole cent lost. The repair for a one-off conversion is to round first and convert second: `Int((price * 100).rounded())` gives `1999`. The default rule of `rounded()` is `.toNearestOrAwayFromZero`, the schoolbook rule, so `2.5` becomes `3.0`; `rounded(.toNearestOrEven)` rounds halves to the even neighbour instead, which avoids an upward bias when many halves are rounded. ## Float makes it worse, not better `Float` stores only a 23-bit significand (`Float.significandBitCount` is 23), roughly half the precision of `Double`. Whole numbers above 16,777,216 are no longer all representable: the compiler warns "'16777217' is not exactly representable as 'Float'; it becomes '16777216'". A cart total in `Float` reaches visible errors at much smaller sums. Use `Float` only where an API or a GPU format requires 32-bit values. ## Storing money exactly The robust fix is to stop storing money as a binary fraction at all: 1. Store **integer minor units**: `priceCents: Int`. Addition, subtraction and comparison of `Int` values are exact, so a cart of `[10, 20, 30]` cents totals exactly `60`. 2. Get the integer **from the source**: a backend that sends cents, or parsing the decimal string directly into whole and fractional parts, rather than parsing into `Double` and multiplying. 3. Round **once, at a defined point**, when a rate is applied (tax, a percentage discount, a currency conversion), with a rounding rule the business has chosen. 4. Convert to a display string at the very edge; formatting and Foundation's decimal type belong with Foundation and text formatting. | Representation | Sum of 0.10 + 0.20 + 0.30 | Exact? | Notes | |---|---|---|---| | `Double` | `0.6000000000000001` | No | Default for literals; fine for measurements | | `Float` | larger errors sooner | No | About half the precision of `Double` | | `Int` cents | `60` | Yes | Needs an explicit scale and a rounding rule for rates | ## What not to do - Rounding the **displayed** total with `rounded()` hides the drift on screen but leaves the stored total wrong for comparisons and further sums. - Comparing totals with `==` after floating-point arithmetic is fragile; comparing within a tolerance is the general floating-point remedy, but for money the exact integer model removes the need. - Watch for special values: `0.0 / 0.0` produces NaN, which compares unequal to everything including itself (the compiler even warns that `.nan == .nan` "is always false"), and converting NaN with `Int(_:)` traps. Use `isNaN` or `isFinite` before converting. `Double` remains the right type for measurements, ratios and progress fractions, where a relative error of about one part in 10^16 is irrelevant. Money is different because people check it to the last cent, and because the same amount is often computed twice, once on the device and once on a server, and the two must agree. ## Diagnosing it in an existing app - Search the model layer for prices declared as `Double` or `Float`, and for `Int(` calls applied to a multiplied price; each one is a candidate for a lost cent. - Print the raw stored value rather than a formatted string: formatting rounds for display and hides the drift you are looking for. - Write a test that adds a long list of small prices and compares the result with an integer total; the floating-point version fails it quickly.

  • Why not keep Double and call rounded() on the total before showing it?
    That fixes the screen, not the data. The stored total is still off, so comparing it with a server's total, checking a free-shipping threshold or adding more items keeps carrying the error, and rounding at each step is an ad hoc patch. Integer cents make addition, subtraction and comparison exact, leaving rounding to the few places where a rate is multiplied in.
  • How does Swift's `rounded()` treat 2.5, and why might a ledger prefer `rounded(.toNearestOrEven)`?
    `rounded()` uses the schoolbook rule `.toNearestOrAwayFromZero`, so `2.5` becomes `3.0`. Rounding every half upward biases a large set of values upward; `.toNearestOrEven` sends halves to the even neighbour (`2.5` to `2.0`, `3.5` to `4.0`), so the bias cancels out over many roundings. The rule should be a business decision, written down once.

Measuring a shelf with a ruler marked only in sixteenths of an inch: every length you write down is the nearest mark, and adding many of them lets the small misses pile up. Counting coins never has that problem, which is why the fix is to count cents.

  • Double is exact to 15 digits, so a sum of prices cannot drift.
  • Int(price * 100) rounds a price to the nearest cent.
  • Switching the prices to Float fixes the rounding error.
  • The extra digits are a print artefact; the stored total is exactly 0.6.
  • Rounding the displayed total makes the stored amounts correct.