Comparing float values in PHP

I had to learn this the hard way. It seems in php 27.64 is just not quite 27.64 , but something close to it ( that's what some people say here anyway: http://www.php.net/ternary ) .

And that's why the following code wouldn't echo the text "dude" as you might think it should:

  1.  
  2. < ?php
  3. function t($amount){
  4. $amountdue=10.00+2.88+2.88+2.88+9.00;
  5.  
  6. echo "amountdue: $amountdue, amount: $amount\n";
  7. if($amountdue == $amount) echo "dude\n";
  8. else echo "but still no match\n";
  9. }
  10. $amount=27.64;
  11. t($amount);
  12. ?>
  13.  

Run this script and you should see:

amountdue: 27.64, amount: 27.64
but still no match

That's the dumbest thing I've ever seen. A similar code written in C gives the good results. Isn't php written in C? They should have copied C's good behavior.
If conversion from float to string gives the right results, why not use the same results when comparing float values?
So if you're having this problem it seems this will work:

  1.  
  2. if((string)$amountdue == (string)$amount) {
  3.  

The fact that php can't compare float values reliably and that you have to resort to this to make it work just makes php look bad.

7 thoughts on “Comparing float values in PHP

    1. Well it’s not just sad it’s stuppid. I understand this might not work for high precision, numbers with a lot of decimals but for stuff like 2.64 compared to 2.64 it’s just stupid. If the comparison works in C it should work just as well in php.

Leave a Reply