# Thread: Modulus Calculation Incorrect - I Think?

1. ## 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.

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

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

3. 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.

4. 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.

5. Originally Posted by TheRedDevil
Please be aware that fmod has floating point issue, so you cannot trust it either
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.

PHP Code:
``` \$mod = fmod(1, 0.2); echo "Got \$mod, expected 0\n"; \$mod = fmod(0.25, 0.05); echo "Got \$mod, expected 0\n";  ```
Here's a function that seems to produce the correct answer in these cases.

PHP Code:
``` function yetAnotherMod(\$dividend, \$divisor) {     \$fractionalRemainder = \$dividend / \$divisor - floor(\$dividend / \$divisor);     return \$fractionalRemainder * \$divisor; }  ```

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

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•