Decimal Module — ELI5
Try this in Python: 0.1 + 0.2. You’d expect 0.3, right? Instead you get 0.30000000000000004. That tiny error is why banks don’t use regular floating-point numbers.
Here’s the analogy: regular floats are like measuring with a ruler that only has marks every quarter inch. You can get close to any measurement, but not exact. For most things — games, graphics, science — “close enough” is fine.
But money is different. If you’re calculating someone’s bank balance, being off by even a fraction of a penny is a problem. Multiply that tiny error across millions of transactions and you’re losing (or inventing) real dollars.
Python’s decimal module is like switching to a ruler with marks at every penny. It stores numbers the way humans write them — 0.1 is exactly one-tenth, not a tiny approximation.
The trade-off? It’s slower than regular math. Computers are built to do float math fast. Decimal math requires more work behind the scenes. For a banking app processing thousands of transactions, the precision is worth the speed cost. For a video game calculating physics at 60 frames per second, it’s not.
You also get to control exactly how rounding works. Should 2.5 round to 2 or 3? With regular floats, Python decides. With decimals, you choose the rounding rule — which matters a lot when regulations say “round half to even” but your gut says “round up.”
One thing to remember: The decimal module exists because computers can’t perfectly represent most decimal fractions as floats. When exactness matters — money, accounting, financial reporting — use Decimal instead of float.
See Also
- Python Atexit How Python's atexit module lets your program clean up after itself right before it shuts down.
- Python Bisect Sorted Lists How Python's bisect module finds things in sorted lists the way you'd find a word in a dictionary — by jumping to the middle.
- Python Contextlib How Python's contextlib module makes the 'with' statement work for anything, not just files.
- Python Copy Module Why copying data in Python isn't as simple as it sounds, and how the copy module prevents sneaky bugs.
- Python Dataclass Field Metadata How Python dataclass fields can carry hidden notes — like sticky notes on a filing cabinet that tools read automatically.