Fwd: Re: [PHP] Strange variable compariso result
| From: | Christopher G.Morlier | Date: | Fri, 18 Oct 2002 15:21:57 +0000 |
| Subject: | Fwd: Re: [PHP] Strange variable compariso result | ||
| Groups: | php.general | ||
| Request: | Send a blank email to php-general+get-120520@lists.php.net to get a copy of this message | ||
Hi Marcello,
When dealing with floating point numbers in just about any language, there is a potential for round of errors. If you use the identical algorithm on the same machine to calculate the values, then it "should" not be a problem, but good programming style is to assume that it will be a problem.
Typically, you should decide on the precision level that you care about. For example, if I were comparing prices in dollars, then my precision would probably be 0.005 (half a cent), because the numbers will round off to the same value. Therefore, you if statement should look like:
if(abs($tot->checksum-$total)<$precision) {
Hope this helps.
-Chris
At 03:27 PM 10/18/2002 -0100, you wrote:
Hi to all. I have a very strange result from this code: I have a query that get a "select sum(columnname) as checksum from table" and a $total variable passed by a Form in post method . I manage both variables as string. After i make $tot=mysql_fetch_object($query_check_ordine);if(($tot->checksum-$total)!=0) { echo " There is a problem"; exit; } else { echo "OK"; }After this i tried to print the 2 values and both are, for example, 9.3 . But if i sottract the 2 variables i obtain 3.5527136766005E-15 instead of 0 . I think that PHP automatically try to evaluate the strings as floats (this is i want too). I tried to compare with != the two variables to see if them are equals and PHP say that the are not equal, but if i print them, them are equals. I tried to settype to floats directly the variables and the result is the same. After all if i settype to string directly the variables the comparison occur correctly. Have you any idea of this behaviour?? Thanks in advice, Bye Marcello -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php