|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
[1999-11-26 16:07 UTC] aulbach at unter dot franken dot de
<?
$b=8.28;
echo $b*100;
echo "<BR>";
echo floor($b*100);
?>
Results in:
828
827
Of course this happens with many other numbers too. (17.08, 18.40, 8.20 ...)
Same Problem is with (int) or anything which seems to convert it to an integer. Even
printf("%d",$b*100); returns 819 not 820.
It is not fully understandable how this could happen - it seems to be a problem in the underlying math-lib?
In my opinion, a float of 828 should always result in integer 828, independent of the binary representation.
Fix in this case: Using round() instead.
PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits
|
|||||||||||||||||||||||||||
Copyright © 2001-2026 The PHP GroupAll rights reserved. |
Last updated: Sun Jun 14 09:00:02 2026 UTC |
There are some things which I will say to this good explanation: 1. This was of course clear for me, why this happens. But, sorry, Ramus, I'm not sharing your opinion, that you have to take care about rounding problems by yourself. In my eyes this keeps an error: The function doesn't do, what you expect and the results could be very ugly. See down. 2. The float number was printed out as "828" and not as "827.99999999999999999". So there must be an explizit float conversion, which does it "right". 3. Ok, I understand, why round(9.5) is not 10, but every simple pocket calculator does this simple thing "right". [Or Oracle for example: SQL> select trunc(8.28*100.0,0) from dual; TRUNC(8.28*100,0) ----------------- 828 mySQL of course too.] 4. For this business applications this behavior of the database mow saved me my live, cause I could see, if my change in the program works right: The resulting difference has been above 450 Deutschmark (about $ 200) - this happens when you calculate about 400,000 operations with this small error. If you make this little error every day over a year you pay about $60,000 too much (or too less).