13

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?

Community
  • 1
  • 1
Mark Amery
  • 143,130
  • 81
  • 406
  • 459
  • 4
    You made me lol at "PHP being the best of all". It is one of the most magical, though, which may be why it hides the precision error from you, while it obviously is still there. – GolezTrol Nov 15 '15 at 23:07

1 Answers1

21

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

Mark Amery
  • 143,130
  • 81
  • 406
  • 459
lafor
  • 12,472
  • 4
  • 32
  • 35