DEV Community

P Giri Kishore
P Giri Kishore

Posted on

0.1 + 0.2 != 0.3?

Can you guess the output of the following code?

output

If you thought the output was "Equal", you're not alone.

We know computers store data in 0s and 1s (binary format). While integers can be accurately converted to binary format, when it comes to floating point numbers this conversion is not quite accurate. Numbers such as 1/2, 1/4, 1/8 can be expressed precisely because the denominators use multiple of 2, while other floating point numbers can't be expressed accurately. (For the simplicity of this post, we will not get into the conversion of floating point numbers to binary)

Since the exact value of such floating point numbers cannot be determined, the processor stores a value close to the actual number in binary format. For this reason we do not get the expected output for any arithmetic operations performed on such floating point numbers.

Explanation

Top comments (0)