Ad space (banner)
🐍Python Lessons
Lesson 58 / 69

Watch Out for Floating-Point Rounding Errors

This lesson covers the rounding errors that arise when a computer handles decimals, so you understand where to be careful in amount calculations. It's written for anyone searching "Python 0.1 0.2 floating point error".

Because computers represent decimals in binary, even a simple calculation like 0.1 + 0.2 can come out slightly off from exactly 0.3. Display it, and you can see the error directly; compare it, and it comes out False. This isn't unique to Python — it's a consequence of how computers work in general, shared across many programming languages.

The sample code shows that running 0.1 + 0.2 produces the error-laden value 0.30000000000000004, and that comparing 0.1 + 0.2 == 0.3 comes out False. It's one of the first surprises many beginners encounter, and it's an eye-opening experience that overturns the assumption that "a computer's arithmetic is always exact."

When floating-point error is a real problem, like amount calculations, you need a workaround — using the decimal module, for example. There's also a function, math.isclose(), that assumes this error exists and compares "are these close enough?" rather than "are these exactly equal?"

In accounting systems and e-commerce price calculations, this kind of error can produce unexpected discrepancies in amounts, so real-world code commonly uses a dedicated library or integer-based arithmetic instead. Accounting for this characteristic is essential.

Python
OUTPUT

💡 The Python engine may take a few seconds to load the first time you run code.

Ad space (banner)
Ad space (in-article)