note 27585 added to language.operators.arithmetic

From: Date: Thu, 12 Dec 2002 01:27:11 +0000
Subject: note 27585 added to language.operators.arithmetic
Groups: php.notes 
Request: Send a blank email to php-notes+get-40774@lists.php.net to get a copy of this message
There's been a lot of discussion about floating point peculiarities with several solutions. There are going to be cases where each of the suggestions will fail. My advice is that if you're expecting something to be an integer but you've used floating point arithmetic to get it, use the round function to make sure it's an integer. Here's an example that shows how the other solutions presented can fail, and how rounding can work. This works on win2k with php 4.2.3. function showExpr($expr) { global $a, $b; echo $expr.': '; eval('echo '.$expr.';'); echo "\n"; } $a = 15 / 11 * 11; // 15, right? $b = 3; showExpr('$a'); // 15 showExpr('$b'); // 3 showExpr('$a / $b'); // 5 // These three lines were suggested by earlier posts, but // they all output 4 instead of 5. showExpr('(int)($a / $b)'); // this gives 4, not 5 showExpr('floor($a / $b)'); // this gives 4, not 5 showExpr('(int)($a-($a % $b))/$b'); // this gives 4, not 5 // Here's my solution, which outputs 5. showExpr('(int)(round($a) / round($b))'); -- http://www.php.net/manual/en/language.operators.arithmetic.php http://master.php.net/manage/user-notes.php?action=edit+27585 http://master.php.net/manage/user-notes.php?action=delete+27585 http://master.php.net/manage/user-notes.php?action=reject+27585

« previous php.notes (#40774) next »