Hacker’s Guide to Visual FoxPro
An irreverent look at how Visual FoxPro really works. Tells you the inside scoop on every command, function, property, event and method of Visual FoxPro.
MOD()
The % operator and MOD()
both compute the modulus of a pair of numbers. For those who never liked math in the first place, that’s the remainder when you divide the first number by the second. (Actually, it is for the rest of us, too.) Another way to think of it is as the part you throw away when you apply FLOOR()
to the quotient.
nRemainder = nDividend % nDivisor
nRemainder = MOD( nDividend, nDivisor )
Parameter |
Value |
Meaning |
nDividend |
Currency, Double, Integer, Numeric |
The number being divided. (The number after "goes into.") |
nDivisor |
Currency, Double, Integer, Numeric |
The number doing the dividing. (The number before "goes into.") |
nRemainder |
Number |
The remainder when nDividend is divided by nDivisor. |
MOD()
and % are pretty straightforward when dealing with positive numbers, but they get interesting when one or both of the numbers is negative. The key to understanding the results is the following equation:
MOD(x,y) = x - (y * FLOOR(x/y))
Since the mathematical modulo operation isn’t defined for negative numbers, it’s a pleasure to see that the FoxPro definitions are mathematically consistent. However, they may be different from what you’d initially expect, so you may want to check for negative divisors or dividends.
A little testing (and the manuals) tells us that a positive divisor gives a positive result while a negative divisor gives a negative result.
MOD()
is most useful when you want to set up intervals of some sort. For example, you might use it in a DynamicBackColor condition to get alternating colors in a grid.
? 3%10 && Returns 1
? MOD(22, 10) && Returns 2
? MOD(-7, 3) && Returns 2
? MOD(-7, -3) && Returns -1
? MOD(7, -3) && Returns -2
The type of the result depends on the divisor and the dividend. When you mix Currency and Numeric or Integer, the result is always Currency. But when you mix Currency with Double, the divisor determines the result type, which is as it should be. The behavior of Currency with numbers feels like a bug to us. In any case, the various numeric types should all behave the same way. |