Just as 1/3
cannot be accurately represented in decimal form, 0.1
also faces representation challenges in binary due to Javascript numbers being binary floating point values.
When we add 0.2 + 0.1
in Javascript, the result is 0.30000000000000004
. Try it in your browser console for proof.
For Javascript's 64-bit floating point values, only 53 bits are allocated to store the mantissa. This results in 0.1
in binary rounded off to 53 bits equating to
0.1000000000000000055511151231257827021181583404541015625
.
The same logic applies to represent 0.2
in binary and when added together, the accurate total comes to
0.3000000000000000444089209850062616169452667236328125
.
This means that while we might perceive 0.1
+ 0.2
as 0.3
, the actual computer calculation rounds off to show 0.30000000000000004
.
Furthermore, even the decimal value 0.3
struggles with exact binary representation.
It is stored as the binary equivalent of
0.29999999999999993338661852249060757458209991455078125
, contributing to why
0.2 + 0.1 == 0.3
evaluates to
false
in Javascript.
Conversion Rationale
A decimal number can only have an exact binary representation if the denominator of its simplest fractional form has 2
as its sole prime factor.
For instance,
0.1
converts to 1/10
, where 10
includes prime factors 2
and 5
, preventing an exact binary conversion.
On the other hand, 0.5
translates to 1/2
, where the denominator's only prime factor is 2
, allowing for an accurate binary representation.