DEV Community

loading...
Cover image for JavaScript Interview Question #32: 0.1 + 0.1 + 0.1 === 0.3

JavaScript Interview Question #32: 0.1 + 0.1 + 0.1 === 0.3

coderslang profile image Coderslang: Become a Software Engineer Originally published at learn.coderslang.com on ・1 min read

js-test-32

What will be logged to the console?

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

At a first glance, the answer is true as 0.1 + 0.1 + 0.1 is obviously equal to 0.3 .

But that’s only before we get into the details of how the numbers are represented in JavaScript.

If you try to execute the statement console.log(0.1 + 0.2) in JS, you’ll get a number 0.30000000000000004.

This happens because in JavaScript and quite a few other programming languages some decimal numbers can't be represented exactly as they are.

For example 0.1 in binary will result in an endless fraction, the same way as 1/3 becomes 0.333(3) in the decimal number system.


ANSWER: false will be logged to the console.

Learn Full-Stack JavaScript

Discussion (4)

pic
Editor guide
Collapse
gyandeeps profile image
Gyandeep Singh

It even gets more interesting with subtraction.
0.3 - 0.1 = 0.19999999999999998

Collapse
coderslang profile image
Coderslang: Become a Software Engineer Author

Absolutely! And the reason is the same.

Collapse
superfola profile image
Alexandre Plateau

Same should also happen in many languages implementing the IEEE 754, great question!

Collapse
coderslang profile image