Destructuring Tweets – Episode 4 – Summing Up
Welcome to my series about destructuring one of those frequently shared JavaScript quizzes on Social Media. This is the fourth episode featuring one of the oldest JS tricks!
The Snippet
console.log(0.1 + 0.2);
console.log(0.1 + 0.2 == 3);
console.log(0.1 + 0.2 === 3);
What we have here seems to be relatively simple at first glance. The author creates three console logs. The first features an addition of 0.1 and 0.2, and the second and third compare the result to 0.3 with two different operators.
The first operator ==
is called “Equal”, the second ===
“Strict Equal”. Both return a boolean value, indicating whether the first and second statement is the same. So, a console.log
either outputs true
or false
.
The Output
Well, the output is easy here, isn't it? It should be:
– 0.3
– true
– true
Surprisingly enough, none of these is correct!
It's actually:
– 0.30000000000000004
– false
– false
The two falses are evident in that context. Since the first output is this odd (pun intended) number, the addition is indeed not equal to 0.3
.
We end up with the fundamental question of why the hell does 0.1 + 0.2
equal 0.30000000000000004
.
The Analysis
For that question to answer, we need to know that computers must cut off decimal numbers at some point. Given two floating-point numbers, JavaScript tries to return the same.
Now, let's stay in the decimal (digits from 0 to 9). How'd you expect a computer to comprehend the number ⅓? It can't just think about it as a repeating decimal and note it down as one. What you need to do at one point is to cut it off. The last digit gets rounded, and that's it.
As you may already know, computers work in binary (digits from 0 to 1). Of course, the same problem exists there! Let's write down 0.1 in binary:
0.0001100110011001100110011...
Notice how “0011” repeats itself over and over again? That's exactly the issue here. JavaScript reserves 52 bits for the fraction; after that, the number gets cut off and rounded. That's where it gets slightly higher than 0.1.
Mathematical evidence is beyond my article's scope, but I will add a link with detailed information on that.
Further Reading
– The two number types of JavaScript
– Mathematical evidence
– toFixed
is a possible API to overcome these issues
– Double Precision Binary Floating Point Format as used by JavaScript numbers