As described in Is floating point math broken?, 0.1 + 0.2
evaluates to 0.30000000000000004
in most programming languages.
However, PHP, presumably due to being the best of all the programming languages, is able to calculate 0.1 + 0.2 correctly:
php > echo 0.1 + 0.2;
0.3
php > var_dump(0.1 + 0.2);
float(0.3)
However, despite the output shown above, 0.1 + 0.2 != 0.3:
php > var_dump(0.1 + 0.2 == 0.3);
bool(false)
What's going on here?
Note that the mantissa is composed of recurring digits of 0011 . This is key to why there is any error to the calculations - 0.1, 0.2 and 0.3 cannot be represented in binary precisely in a finite number of binary bits any more than 1/9, 1/3 or 1/7 can be represented precisely in decimal digits.
In this article, we will see why 0.3 – 0.2 is not equal to 0.1 in Python. The reason behind it is called “precision”, and it's due to the fact that computers do not compute in Decimal, but in Binary. Computers do not use a base 10 system, they use a base 2 system (also called Binary code).
Conclusion. I was super surprised to learn that 0.1 + 0.2 is actually supposed to equal 0.30000000000000004 in JavaScript because of floating point math.
Your language isn't broken, it's doing floating point math. Computers can only natively store integers, so they need some way of representing decimal numbers. This representation is not perfectly accurate.
PHP has a precision
configuration value which sets the number of significant digits displayed in floating point numbers. It is 14 by default, which is the reason 0.1 + 0.2
is displayed as 0.3
.
If, however, you do this:
ini_set('precision', 17);
echo 0.1 + 0.2;
you get 0.30000000000000004
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With