Tag Archives: float

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. span style="color: #ff0000;">"amountdue: $amountdue, amount: $amount\n""dude\n""but still no match\n"

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.  

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.