-1

Why does 1070 % 21,4 gives a different result in the windows calculator and .net?

(.Net result is 7.1....)

The result should always be 0. I understand a difference with large numbers, but these small numbers should work, IMHO.

Thanks a lot!

BendEg
  • 20,098
  • 17
  • 57
  • 131
  • 9
    The .NET result _is not_ 7.1.It's 7.1 x 10^-14, or 0.000000000000071. And, if you're wondering "why is it 7.1 x 10^-14?" see [this question](https://stackoverflow.com/questions/588004/is-floating-point-math-broken). – ProgrammingLlama Apr 04 '19 at 13:41
  • 1
    It's 0 but resul type is double https://dotnetfiddle.net/tWUzhC – xdtTransform Apr 04 '19 at 13:43
  • 2
    Small numbers are just as bad as big numbers when it comes to floating point maths - eg in .NET `0.1 + 0.2 == 0.3` is `false`. – James Thorpe Apr 04 '19 at 13:45
  • 1
    My bad, I've missed the exponential number... – BendEg Apr 04 '19 at 13:46
  • And it Always cool to read the Lippert serie of article [Floating Point Arithmetic](https://blogs.msdn.microsoft.com/ericlippert/tag/floating-point-arithmetic/page/2/) – xdtTransform Apr 04 '19 at 13:51

1 Answers1

5

Its all in the docs for the % operator. Its floating point remainder, not modulo. If you want something compatible with Calculator use this function

For example:

private static void ShowRemainders(double number1, double number2)
{
   var formula = $"{number1} / {number2}";
   var ieeeRemainder = Math.IEEERemainder(number1, number2);
   var remainder = number1 % number2;
   Console.WriteLine($"{formula,-16} (.IEEE) = {ieeeRemainder,18}");
   Console.WriteLine($"{formula,-16} (.NET)  = {remainder,18}");
}
Steve Todd
  • 1,250
  • 6
  • 13