Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can PHP calculate 0.1 + 0.2 when other languages fail?

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?

like image 561
Mark Amery Avatar asked Nov 15 '15 23:11

Mark Amery


People also ask

Why is 0.1 0.2 === 0.3 false and how can you ensure precise decimal arithmetics?

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.

Why 0. 1 0. 2 is not 0. 3 python?

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).

What is the output of 0.1 0.2 in JavaScript?

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.

Is floating point arithmetic broken?

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.


1 Answers

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

like image 179
lafor Avatar answered Oct 02 '22 01:10

lafor