DEV Community

Matsu
Matsu

Posted on

Exploring JavaScript's Floating Point Arithmetic: Why (0.1 + 0.2) !== 0.3

Have you ever encountered unexpected results when working with floating-point numbers in JavaScript? One common surprise is the result of (0.1 + 0.2) === 0.3, which evaluates to false. Let's delve into the reasons behind this phenomenon and understand the quirks of floating-point arithmetic in JavaScript.

The Surprising Result

console.log(0.1 + 0.2 === 0.3); // Output: false
Enter fullscreen mode Exit fullscreen mode

At first glance, it might seem logical that adding 0.1 and 0.2 should equal 0.3. However, due to the nature of floating-point arithmetic, the result is not always what we expect.

Floating-Point Precision
JavaScript, like many programming languages, uses the IEEE 754 standard for representing floating-point numbers. While this standard provides a wide range of representable numbers, it also introduces limitations in precision.

In binary representation, 0.1 and 0.2 are recurring fractions that cannot be precisely represented in a finite number of binary digits. As a result, the addition of these two imprecise values may yield a result that is slightly different from 0.3.

Demonstrating Precision Issues

console.log(0.1 + 0.2); // Output: 0.30000000000000004
Enter fullscreen mode Exit fullscreen mode

The result of 0.1 + 0.2 is not exactly 0.3 but rather a close approximation due to floating-point rounding errors.

Mitigating Precision Errors
To handle precision issues when working with floating-point numbers in JavaScript, it's essential to be aware of the limitations and employ strategies such as rounding or using integer arithmetic where appropriate.

Conclusion: Understanding Floating-Point Arithmetic
While (0.1 + 0.2) !== 0.3 may seem puzzling at first, it's a consequence of the inherent limitations of floating-point arithmetic in JavaScript. By understanding these limitations and being mindful of precision issues, you can write more robust and predictable code.

Next time you encounter unexpected results with floating-point numbers in JavaScript, remember to consider the nuances of floating-point arithmetic and apply appropriate techniques to mitigate precision errors.

Console You Later!

Top comments (0)