Advertisement

Sooner or later, most developers hit the moment where adding two simple decimals produces a bizarre trailing result, or a total is off by a fraction of a cent. It looks like a bug in the language, but it is actually a fundamental property of how computers store decimal numbers — and it is the reason you should never hold money in an ordinary floating-point value.

Understanding why saves you from a class of costly, embarrassing errors.

Why 0.1 + 0.2 misbehaves

Floating-point numbers store values in binary, and many perfectly ordinary decimal fractions cannot be represented exactly in binary — much as one-third cannot be written exactly in decimal. The computer stores the closest approximation it can, and those tiny approximation errors accumulate through arithmetic, producing results that are almost, but not exactly, right.

This is not a defect to be fixed; it is an inherent trade-off of a format designed for a huge range of values, not exact decimals.

Advertisement

Why money is the danger zone

For scientific measurements, minuscule rounding is usually fine. For money, it is not: fractions-of-a-cent errors accumulate across many transactions, totals fail to reconcile, and users notice when a bill is a penny wrong. Financial calculations demand exactness that floating-point simply does not promise.

The failure is insidious because small cases often look correct, and the errors only surface at scale or in edge cases — exactly where money matters most.

What to do instead

The standard solutions are to work in the smallest whole unit — storing amounts as integer cents rather than fractional currency — or to use a dedicated decimal type designed for exact base-ten arithmetic, which many languages provide. Both avoid the binary-approximation problem entirely.

The rule of thumb is simple and worth memorising: floating-point is for measurements, not money. Store currency as integers or a proper decimal type, and this whole category of bug disappears.