0

Hi I'm having this really weird issue with C#.

I'm trying to do a modulu operation:

double stepSize = 3.6;
if (180.0 % stepSize != 0) DoStuff();

And 180.0 % 3.6 = 0 -> "proof"

But for some reason C# returns: 3.6

Do any one have an explanation for that

Bjqn
  • 146
  • 2
  • 19
  • Also see: [Is floating point math broken?](https://stackoverflow.com/questions/588004/is-floating-point-math-broken#588014) – Nisarg Shah Apr 04 '18 at 10:10
  • https://stackoverflow.com/questions/906564/why-is-modulus-operator-not-working-for-double-in-c/906628 – dropoutcoder Apr 04 '18 at 10:10
  • `3.6` cannot be represented exactly. The closest `double` has a decimal representation of `3.6000000000000001`, which is slightly greater. As a result, there's a significant nonzero remainder. Note that `1800.0 % 36.0 == 0.0` -- small integers can be represented exactly, even in floating-point calculations. – Jeroen Mostert Apr 04 '18 at 10:18

1 Answers1

3

The problem is the floating-point arithmetics and its inability to represent all decimal numbers precisely. A simple test reveals the differences:

decimal type:

Console.WriteLine(180m % 3.6m); // 0.0

float type:

Console.WriteLine(180f % 3.6f); // 4.768372E-06

double type:

Console.WriteLine(180d % 3.6d); // 3.6
Ondrej Tucny
  • 27,626
  • 6
  • 70
  • 90