DEV Community

P Giri Kishore
P Giri Kishore

Posted on

2 1

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

Image of Datadog

The Essential Toolkit for Front-end Developers

Take a user-centric approach to front-end monitoring that evolves alongside increasingly complex frameworks and single-page applications.

Get The Kit

Top comments (0)

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up