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

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (0)

The Most Contextual AI Development Assistant

Pieces.app image

Our centralized storage agent works on-device, unifying various developer tools to proactively capture and enrich useful materials, streamline collaboration, and solve complex problems through a contextual understanding of your unique workflow.

πŸ‘₯ Ideal for solo developers, teams, and cross-company projects

Learn more

πŸ‘‹ Kindness is contagious

Please leave a ❀️ or a friendly comment on this post if you found it helpful!

Okay