Sergey - 3 months ago 17

C# Question

Recently I discovered that C#'s operator

`%`

`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.

Is

`a % b`

`a - b*Math.Round(a/b)`

EDIT: Answering to James L,

Answer

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));
Console.ReadLine();
}
```

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)`

.