% Operator (C# Reference)

The remainder operator % computes the remainder after dividing its first operand by its second operand.

User-defined types can overload the % operator. When the % is overloaded, the remainder assignment operator %= is also implicitly overloaded.

All numeric types support the remainder operator.

Integer remainder

For the integer operands, the result of a % b is the value produced by a - (a / b) * b. The sign of the non-zero remainder is the same as that of the first operand, as the following example shows:

Console.WriteLine(5 % 4);   // output: 1
Console.WriteLine(5 % -4);  // output: 1
Console.WriteLine(-5 % 4);  // output: -1
Console.WriteLine(-5 % -4); // output: -1

Floating-point remainder

For the float and double operands, the result of x % y for the finite x and y is the value z such that

  • the sign of z, if non-zero, is the same as the sign of x;
  • the absolute value of z is the value produced by |x| - n * |y| where n is the largest possible integer that is less than or equal to |x| / |y| and |x| and |y| are the absolute values of x and y, respectively.

For information about the behavior of the % operator with non-finite operands, see the Remainder operator section of the C# language specification.

Note

This method of computing the remainder is analogous to that used for integer operands, but differs from the IEEE 754. If you need the remainder operation that complies with the IEEE 754, use the Math.IEEERemainder method.

The following example demonstrates the behavior of the remainder operator for float and double operands:

Console.WriteLine(-5.2f % 2.0f); // output: -1.2
Console.WriteLine(5.0 % 2.2);    // output: 0.6
Console.WriteLine(.41 % .2);     // output: 0.00999999999999995

Note the round-off errors that can be associated with the floating-point types.

For the decimal operands, the remainder operator % is equivalent to the remainder operator of the System.Decimal type.

See also