Why 0.1 + 0.2 isn't 0.3, and what that has to do with money
Notes

Why 0.1 + 0.2 isn't 0.3, and what that has to do with money

Open the calculator in your browser or the developer console, type 0.1 + 0.2, and look at the answer. It won't be 0.3, it'll be this:

0.1 + 0.2
> 0.30000000000000004

This isn't a bug in some particular program - almost every computer in the world counts this way. And hiding behind that little ...0004 tail is the reason developers treat money with special care.

Why it happens

We count in the decimal system, and a computer counts in binary, in zeros and ones. Some fractions that are simple for us go on forever in binary - exactly the way 1/3 turns into 0.3333... without end in decimal. The number 0.1 is one of those: it doesn't fit into memory whole, so it's stored a little imprecisely, rounded to the nearest available value. Add two such imprecise numbers together and the tiny errors surface as that very tail.

The analogy is simple: write 1/3 as 0.3333 and multiply it by three. You get 0.9999, not one. The computer does exactly the same thing, only in binary and with numbers like 0.1.

What this has to do with money

In a single operation the tail goes unnoticed. But picture an invoice where thousands of prices, discounts, and taxes are added up. The tiny errors accumulate, and at some point the total drifts away from reality by a penny, then by a whole hryvnia. For a game that doesn't matter, but for accounting, a cash register, or billing it already means "the books don't balance" - and tracking down where that extra penny came from is painful.

How to do it right

We never keep money in fractional numbers. Inside the system a sum lives either in whole units (for example, in kopecks) or in a special precise type that doesn't round along the way. And the nice-looking 1,200.00 appears only at the very last moment - on the screen, when it's displayed.

Совет

Store the amount in whole units or in a precise type, and format it only when displaying. Then every calculation stays exact and the books balance to the penny.

It's little details like these that make the difference between "seems to work" and "works correctly."

Oleksandr

Oleksandr

Fullstack developer with 8+ years of experience - from industrial automation and hands-on hardware integration to document workflows and chatbots. Currently focused on applied AI, from RAG-based conversational platforms to computer vision.