chaiwei Posted November 26, 2008 Share Posted November 26, 2008 Hi all, I got 2 variable $td and $tc which get the value from the database if(row['side']=='d') $td+=row['amount']; else if (row['side']=='c') $tc+=row['amount']; echo $td; // 3600.29 echo $tc; // 3600.29 if(($td-$tc)<>0){ echo ($td-$tc); //4.54747350886E-13 } By right it should not print any value, right? but where is the 4.54747350886E-13 came from? but if I put echo number_format($td-$tc); //0 It shows me 0 what is happening behind there? Quote Link to comment Share on other sites More sharing options...
The Little Guy Posted November 26, 2008 Share Posted November 26, 2008 try this: if(($td-$tc) != 0){ echo ($td-$tc); //4.54747350886E-13 } Quote Link to comment Share on other sites More sharing options...
corbin Posted November 26, 2008 Share Posted November 26, 2008 4.54747350886E-13 Is .000000000000454747350886, which is ridiculously close to 0. What you're coming across is called floating point inaccuracy. http://en.wikipedia.org/wiki/IEEE_754 It should be mentioned somewhere in there. Quote Link to comment Share on other sites More sharing options...
The Little Guy Posted November 26, 2008 Share Posted November 26, 2008 May want to use the round() function. if(round($td-$tc) != 0){ echo ($td-$tc); //4.54747350886E-13 } Quote Link to comment Share on other sites More sharing options...
corbin Posted November 26, 2008 Share Posted November 26, 2008 The common solution is usually to check if x - y < z where z is a float of arbitrary value, and 1 or both of x and y are floats. Example: <?php $x = 5.34; $y = 5.34; if($x - $y < .0000001) { "x - y is 0!"; } Edit: If the larger number is the one being subtracted, the absolute value must be taken. Quote Link to comment Share on other sites More sharing options...
chaiwei Posted November 26, 2008 Author Share Posted November 26, 2008 if(($td-$tc) != 0){ echo ($td-$tc); 4.54747350886E-13 } same. also is 4.54747350886E-13 I see, I try to echo number_format($tc,50); it shows me 3,600.28999999999950887286104261875152587890625 which is near to 3600.29 So that's why $td-$tc shows me that 4.54747350886E-13 Thanks you guys for helping me out. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.