Sergey Sergey - 3 months ago 17
C# Question

Meaning of "%" operation in C# for the numeric type double

Recently I discovered that C#'s operator

is applicable to double. Tried some things out, and after all came up with this test:

class Program
static void test(double a, double b)
if (a % b != a - b * Math.Truncate(a / b))
Console.WriteLine(a + ", " + b);
static void Main(string[] args)
test(2.5, 7);
test(-6.7, -3);
test(8.7, 4);

Everything in this test works.
a % b
always equivalent to
a - b*Math.Round(a/b)
? If not, please explain to me how this operator really works.

EDIT: Answering to James L, I understand that this is a modulo operator and everything. I'm curious only about how it works with double, integers I understand.


The modulus operator works on floating point values in the same way as it does for integers. So consider a simple example:

4.5 % 2.1

Now, 4.5/2.1 is approximately equal to 2.142857

So, the integer part of the division is 2. Subtract 2*2.1 from 4.5 and you have the remainer, 0.3.

Of course, this process is subject to floating point representability issues so beware – you may see unexpected results. For example, see this question asked here on Stack Overflow: Floating Point Arithmetic - Modulo Operator on Double Type

Is a % b always equivalent to a - b*Math.Round(a/b)?

No it is not. Here is a simple counter example:

static double f(double a, double b)
    return a - b * Math.Round(a / b);

static void Main(string[] args)
    Console.WriteLine(1.9 % 1.0);
    Console.WriteLine(f(1.9, 1.0));

As to the precise details of how the modulus operator is specified you need to refer to the C# specification – earlNameless's answer gives you a link to that.

It is my understanding that a % b is essentially equivalent, modulo floating point precision, to a - b*Math.Truncate(a/b).