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.

6 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 to MihaiCancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.