0
    $totalFileFloat = (float) (str_replace(',', '', $totalFile));
    $total = (float) ($total);
    var_dump([$totalFileFloat, $total]);
    var_dump($totalFileFloat != $total);
    var_dump($totalFileFloat !== $total);
    var_dump($totalFileFloat === $total);
    var_dump($totalFileFloat == $total);

The result from the code is:

array(2) { [0]=> float(183024.22) [1]=> float(183024.22) }

bool(true)
bool(true)
bool(false)
bool(false)

Can someone explain this?

yanko-belov
  • 503
  • 2
  • 6
  • 15

3 Answers3

1

Floating point numbers have limited precision. Have a look in my example

<?php
$x = 8 - 6.4;  // which is equal to 1.6
$y = 1.6;
var_dump($x == $y); // output bool(false)

var_dump(round($x) == round($y)) // output bool(true)
?>

According to the PHP manual we should not compare float numbers directly. For more info please visit http://php.net/manual/en/language.types.float.php.

halfer
  • 19,824
  • 17
  • 99
  • 186
Passionate Coder
  • 7,154
  • 2
  • 19
  • 44
0

The documentation say not to compare floating numbers, but if you need compare you can use bccomp (http://php.net/manual/en/function.bccomp.php)

And here the example:

<?php
$a = 0.17;
$b = 1 - 0.83; //0.17

echo "$a == $b (core comp oper): ", var_dump($a==$b);
echo "$a == $b (with bc func)  : ", var_dump( bccomp($a, $b)==0 );



Result:
    0.17 == 0.17 (core comp oper): bool(false)
    0.17 == 0.17 (with bc func)  : bool(true)
DevAll
  • 124
  • 7
0

This happens probably because $total and $totalFileFloat are not *exactly** the same. var_dump shows it to you as being the same, but in fact it is not. See also http://php.net/manual/en/language.types.float.php#113703