Understanding why 0.1 + 0.2 ≠ 0.3 in programming languages
One of the most surprising behaviors for new programmers is discovering that simple decimal arithmetic doesn't work as expected in most programming languages.
The root cause lies in how computers store decimal numbers using the IEEE-754 standard. Let's examine the actual binary representations:
Try your own calculations and see the floating point imprecision in action:
Important: This behavior is not unique to JavaScript. It occurs in virtually all programming languages that use IEEE-754 floating point arithmetic, including:
The temptation to make fun of JavaScript for this is strong, but it's completely unfounded!
Here are practical ways to handle floating point comparisons and monetary calculations:
Stripe's Solution: Store all monetary values as integers in the smallest currency unit. This completely eliminates floating point precision issues for financial calculations.
Benefits: Perfect precision, no rounding errors, works with all currencies, and follows banking industry standards.