Mod

From Xojo Documentation

Operator

Returns the remainder of the division of two numbers.

Usage

result = number1 Mod number2

Part Type Description
result Integer The remainder (as an Integer) of number1 divided by number2.
number1 Number Any number.
number2 Number Any not null number.

The Mod operator divides number1 by number2 and returns the remainder as result. If either number1 or number2 is a floating-point type, it is first coerced to Int32. If either number1 or number2 is an Int64, then both values are promoted to Int64. If number2 is zero, the result is undefined even if number1 is also zero. The only expected behavior is that the application will not crash. To ensure proper program execution, you should test to ensure that number2 is not zero before using Mod.


NOTE: When converting a floating-point number to an integer, there is always the chance of data loss. The same is true when a floating point value holds a sentinel such as infinity or NaN. Integers do not reserve space for sentinel values, so that information is lost. Converting a floating-point number that represents a sentinel to an Integer yields undefined results.


The Mod operator operates on integers even if it is passed real numbers. For example:

Var r As Integer
r = 5 Mod 2 // r = 1
r = 5 Mod 1.99999 // r = 0

If number1 is negative, then result is negative. For example:

Var r As Integer
r = -10 Mod 3 // r = -1
r = -10 Mod -3 // r = -1
r = 10 Mod 3 // r = 1

Sample Code

These examples use the Mod operator to divide two numbers and return the remainder.

Var r As Integer
r = 10 Mod 3 // r = 1
r = 2 Mod 4 // r = 2
r = 9.3 Mod 2.75 // r = 1
r = 4.5 Mod 1 // r = 0
r = 25 Mod 5 // r = 0

This example allows you to determine if the integer value myInteger is odd or even:

If myInteger Mod 2 = 0 Then // Divisible by 2, so it is even
// Put your code here
Else // myInteger is odd
// Put your code here
End If

See Also

/ (division), \ (integer division), Operator Modulo and Operator ModuloRight functions, Operator precedence.