🧮 Floating-Point Precision Error: Why 0.1 + 0.2 ≠ 0.3?
We often encounter strange results like:
console.log(0.1 + 0.2);
// Output: 0.30000000000000004
But why does this happen?
The reason is Floating-Point Precision Error!
💡 What is Floating-Point Precision Error?
Computers use the binary number system to store decimal values. However, some decimal numbers like 0.1, 0.2, and 0.3 have infinite binary representations. This means they can’t be stored precisely, and tiny inaccuracies (known as precision errors) occur.
📌 Example:
console.log(0.1 + 0.2);
// Expected: 0.3
// Actual: 0.30000000000000004
We expected 0.3
, but got something slightly off. That’s due to how floating-point numbers are represented in memory.
🖥️ Why Does This Happen? (IEEE 754 Standard)
Computers follow the IEEE 754 Standard to represent decimal numbers in binary. Each number is broken into three parts:
- ✅ Sign Bit → Indicates if the number is positive or negative
- ✅ Exponent → Determines how many times to multiply by powers of 2
- ✅ Mantissa (or Fraction) → Holds the actual number value
However, the mantissa has limited length, so many decimal numbers can't be stored exactly, resulting in rounding errors.
🛠️ How to Reduce Precision Errors
✅ Use a Decimal Library (for exact decimal math):
from decimal import Decimal
print(Decimal('0.1') + Decimal('0.2')) # Output: 0.3
✅ Use Rounding (when slight imprecision is okay):
console.log((0.1 + 0.2).toFixed(2)); // Output: "0.30"
✅ Use Epsilon Comparison (machine precision check):
import math
print(math.isclose(0.1 + 0.2, 0.3)) # Output: True
🚀 Why Does It Matter in Real Life?
🔹 Banking Systems – Even a tiny error can cause massive financial loss
🔹 Scientific Computation – Tiny mistakes can derail space missions
🔹 Game Development – A small glitch in the physics engine can ruin the player experience
Conclusion
- 🔸 Computers can’t store all decimal numbers exactly.
- 🔸 Floating-point precision errors cause small but important inaccuracies.
- 🔸 Using techniques like decimal libraries, rounding, or epsilon comparison can help minimize these issues.
[hidden by post author]