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

As described in Is math floating point? , 0.1 + 0.2 is estimated at 0.30000000000000004 in most programming languages.

However, PHP, apparently because it is the best of all programming languages, is able to correctly calculate 0.1 + 0.2:

 php > echo 0.1 + 0.2; 0.3 php > var_dump(0.1 + 0.2); float(0.3) 

However, despite the result shown above, 0.1 + 0.2! = 0.3:

 php > var_dump(0.1 + 0.2 == 0.3); bool(false) 

What's going on here?

+6
source share
1 answer

PHP has a precision value that sets the number of significant digits displayed in floating point numbers. The default is 14, which is the reason that 0.1 + 0.2 displayed as 0.3 .

If you do this:

 ini_set('precision', 17); echo 0.1 + 0.2; 

you get 0.30000000000000004

+9
source

All Articles