php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #12623 mod operator
Submitted: 2001-08-07 11:14 UTC Modified: 2001-08-07 14:22 UTC
From: dosena at altavista dot com Assigned:
Status: Not a bug Package: Math related
PHP Version: 4.0.4pl1 OS: linux (suse)
Private report: No CVE-ID: None
View Add Comment Developer Edit
Anyone can comment on a bug. Have a simpler test case? Does it work for you on a different platform? Let us know!
Just going to say 'Me too!'? Don't clutter the database with that please !
Your email address:
MUST BE VALID
Solve the problem:
7 - 2 = ?
Subscribe to this entry?

 
 [2001-08-07 11:14 UTC] dosena at altavista dot 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;
?>

Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2001-08-07 12:42 UTC] jmcastagnetto@php.net
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.
 
PHP Copyright © 2001-2019 The PHP Group
All rights reserved.
Last updated: Fri Dec 13 11:01:24 2019 UTC