1 out of 1 rated this helpful - Rate this topic

% Operator (C# Reference)

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

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.

class MainClass6
{
    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
*/



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

Concepts

Reference

Other Resources

Did you find this helpful?
(1500 characters remaining)
Community Content Add
Annotations FAQ
Beware of rounding errors
//Try this before relying too heavily on the Modulus operator:
double a = 5.5;
double b = 1.1;
double c = a % b;
// c returns: 1.0999999999999996
// since a(5.5) is perfectly divisibly by b(1.1), shouldn't c=0? This isn't even close!
// Similar results with variables of type: float
// decimal works fine!
Where to notice the round-off errors associated with the double type?
:/