# Modulus Calculation Incorrect - I Think?

Hey guys, this should be a simple situation but I’m crunching some numbers using the modulus operator and something just isn’t right.

This is working correctly:
1161 / 32.25 = 36

This, however, is not:
1161 % 32.25 = 9

If you crunch those numbers, you’ll see that there is no remainder. As such, I have no idea where the value of 9 is coming from. My actual code is below, though it’s not going to help much. Does anybody know of a bug with the modulus operator? Maybe I’m just missing something overly simple.

``````\$Remainder = \$Trade % \$PriceList;
// \$Remainder is 9
``````

I believe PHP only does modulus with integers, so it’s actually doing 1161 % 32.

Try using the fmod function instead. The modulus operator is only intended to work with integers, and anything else tends to lead to unpredictable results.

Please be aware that fmod has floating point issue, so you cannot trust it either, unless your certain the number your compare against is in a specific range not affected.

We ended up writing a code where we converted the number to hundreds (cents, to remove the decimal point), before running modulus and a few other tests to verify the result.

Yup, you seem to be right. I looked through the comments on the fmod doc page, and found a couple examples that produce the wrong answer.

``````\$mod = fmod(1, 0.2);
echo "Got \$mod, expected 0\
";

\$mod = fmod(0.25, 0.05);
echo "Got \$mod, expected 0\
";
``````

Here’s a function that seems to produce the correct answer in these cases.

``````function yetAnotherMod(\$dividend, \$divisor)
{
\$fractionalRemainder = \$dividend / \$divisor - floor(\$dividend / \$divisor);

return \$fractionalRemainder * \$divisor;
}
``````

Thanks guys! Never thought about the decimal issue. The function provided by Jeff worked great!