note 33903 deleted from language.operators.arithmetic by sniper
| From: | sniper@php.net | Date: | Mon, 13 Oct 2003 00:08:49 +0000 |
| Subject: | note 33903 deleted from language.operators.arithmetic by sniper | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-58392@lists.php.net to get a copy of this message | ||
Note Submitter: me@somewhere.com
----
Since Modulo is defined, there is a way to define integer division such that it STAYS in integer
mode and you never have to worry about float rounding problems.
$int_quotient = (int) ( ( $a - $a % $b ) / $b )
The int is merely there for casting the result to a integer.
Take 14 / 4
$a - $a % $b is integer math, and removes the remainder, this ensures a clean division...
14 - 14 % 4 = 14 - 2 = 12 <- Stays integer
By the above step, removing the remainder guarantees the resulting division will yield a whole
number, yes it is a float, but being a whole number, there is no funky floating point artifacts. All
the math till this point has been integer.
12 / 3 = 4.0, which is converted to INT by the cast.
Now, we get.... 4 and 2 as the integer results for 14/3 & 14%3.
Is this correct?
4*3 + 2 = 14, so it works.
Negative cases are funky, but I'm sure this can be modded to deal with 14/-3, and -14/3.
3