On Thu, Feb 18, 2010 at 16:47, Chuck <chuck.carson@xxxxxxxxx> wrote: > Sorry, been doing heavy perl and haven't written any PHP in 3 years so a tad > rusty. > > Can someone explain why the second expression in this code snippet evaluates > to 7 and not 8? > > $a = (int) (0.1 +0.7); > > echo "$a\n"; > > $x = (int) ((0.1 + 0.7) * 10); > > echo "$x\n"; > > $y = (int) (8); > > echo "$y\n"; > The reason why you get 7 instead of 8 is because you are using floating point arithmetic. 0.1 (i.e. the fraction 1/10) does not have a finite representation in base 2 (like you cannot finitely represent 1/3 in base 10). So the number 0.1 is represented in the computer as a number that is strictly less than 0.1 so when you do 0.1+0.7=x then you have x<0.8 in the computer (think 7.9999999...). When you cast to int you just truncate the number, i.e. you chop off the fractional part leaving you with 7. -- Daniel Egeberg -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php