php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login go to bug id or search bugs for
Bug #12623 Submitted: mod operator 2001-08-07 11:14 UTC 2001-08-07 14:22 UTC dosena at altavista dot com Not a bug Math related 4.0.4pl1 linux (suse) No None
[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;
?>
```

## Pull Requests

Add a Pull Request

## History

[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.
```
 Copyright © 2001-2023 The PHP Group All rights reserved. Last updated: Tue Nov 28 14:01:26 2023 UTC