Bug #12623 Updated: mod operator

From: Date: Tue, 07 Aug 2001 16:42:57 +0000
Subject: Bug #12623 Updated: mod operator
References: 1  Groups: php.dev 
Request: Send a blank email to php-dev+get-62444@lists.php.net to get a copy of this message
ID: 12623 Updated by: jmcastagnetto Reported By: dosena@altavista.com Old Status: Open Status: Closed Bug Type: Math related Operating System: linux (suse) PHP Version: 4.0.4pl1 New Comment: The modulus operator is strictly defined for integer numbers, because it "... basically just returns the remainder of an integer division operation ..." (paraphrasing from the K&R book) In this case the floats are truncated to integers and then the modulus operator is applied, i.e. 203.5 turns into 203 17.9 turns into 17 then 203 % 17 = 16 (as expected) Other languages follow this approach, while other round up the float previous to operating on them, in those languages the result would be: "6" And other languages, like Java, have a third behavior in which when using floats, a number of integer substractions is made and a floating point reminder is calculated, see for example: http://softwaredev.earthweb.com/multi/article/0,,12079_630791,00.html (explanation to question 3) BTW, gawk also performs an integer number of substractions, if you try: gawk '{ print (203.5 % 17.9) }' you'll get "6.6" Bottomline, as this is an operator meant to work with integers, make the appropriate conversion for the appropriate results, or implement a modulus function like: function modulus_of ($q, $d) { $rem = $q; while ($rem > $d ) $rem -= $d; return $rem; } which *will* return "6.6" for floats, and should also work on integers. Previous Comments: ------------------------------------------------------------------------ [2001-08-07 11:14:21] dosena@altavista.com Modulus (%) operator i am not sure if the behavior for non-integer operands is defined, so i am not sure how important this actually is check 2035 % 179 = 66 // correct! 203.5 % 17.9 = 16 // incorrect - should be 6.6! <?php echo "2035 % 179 == " . 2035 % 179; echo "<br>\n"; echo "203.5 % 17.9 == " . 203.5 % 17.9; ?> ------------------------------------------------------------------------ Edit this bug report at http://bugs.php.net/?id=12623&edit=1

« previous php.dev (#62444) next »