note 27585 deleted from language.operators.arithmetic by sniper

From: Date: Mon, 13 Oct 2003 00:08:42 +0000
Subject: note 27585 deleted from language.operators.arithmetic by sniper
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-58390@lists.php.net to get a copy of this message
Note Submitter: rjbogue at hotmail dot com ---- 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))');

« previous php.notes (#58390) next »