% Operator (C# Reference)

The remainder operator (%) computes the remainder after dividing its first operand by its second. All numeric types have predefined remainder operators.

Remarks

The formula a % b will always return a value on the range (-b, b), exclusive (it can never return b or -b), keeping the sign of the dividend. For integer division, the remainder operator satisfies the rule a % b = a - (a / b) * b.

This is not to be confused with canonical modulus, which satisfies a similar rule but with floored division and returns values on the range [0, b). C# does not have an operator for canonical modulus. However, the behavior is the same for positive dividends.

User-defined types can overload the % operator (see operator). When a binary operator is overloaded, the corresponding assignment operator, if any, is also implicitly overloaded.

Example

class MainClass
{
    static void Main()
    {
        Console.WriteLine(5 % 2);       // int
        Console.WriteLine(-5 % 2);      // int
        Console.WriteLine(5.0 % 2.2);   // double
        Console.WriteLine(5.0m % 2.2m); // decimal
        Console.WriteLine(-5.2 % 2.0);  // double
    }
}
/*
Output:
1
-1
0.6
0.6
-1.2
*/

Comments

Note the round-off errors associated with the double type.

See Also

C# Reference
C# Programming Guide
C# Operators