1

I am trying to get remainder of 2 double using % operator

double x = 965.606698735538;
double y = 482.803349367769;
var mod = x % y;

Expected value is 0

Actual value is 482.803349367769

Can someone help why its behaving so strange.

Blacktempel
  • 3,935
  • 3
  • 29
  • 53
paresh
  • 56
  • 3

1 Answers1

3

This is a quirk of binary floating point arithmetic.

The closest (IEEE754) double to 482.803349367769 is 482.80334936776898757671006023883819580078125

The closest double to 965.606698735538 is 965.6066987355379751534201204776763916015625

As you can see the latter is not exactly twice the former; in fact it is just under twice that. Which accounts for the large remainder that you see.

You need to be careful when using % with floating point arguments.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483