% Operator (C# Reference)
The remainder operator
% computes the remainder after dividing its first operand by its second operand.
All numeric types support the remainder operator.
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
- the sign of
z, if non-zero, is the same as the sign of
- the absolute value of
zis the value produced by
|x| - n * |y|where
nis the largest possible integer that is less than or equal to
|x| / |y|and
|y|are the absolute values of
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
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.
We'd love to hear your thoughts. Choose the type you'd like to provide:
Our feedback system is built on GitHub Issues. Read more on our blog.