0

I am trying to find out modulo in c# as i know remainder is obtained on doing a modulo b= remainder so here a%b=remainder the same i tried to do like this:

 var distanceFactor = slider.Value % distance;

But the value on debugging of slider.Value= 2.0 and distance =0.1 and distanceFactor i found surprisingly is 0.0999999999.. and i was expecting it to be 0.

Is it due to var ? what could be the reason for this non zero value.? And how to do the solution of this problem ? because on rounding of this 0.0999999999 becomes 0.1 ans my control never go in condition if(distanceFactor==0) (and roundoff is also necessary in current situation).Is there any alternative to achieve it ?

Sss
  • 1,519
  • 8
  • 37
  • 67

1 Answers1

1

This is expected behavior. A floating point number does not exactly represent a decimal number like the type decimal would do. Look at What Every Computer Scientist Should Know About Floating-Point Arithmetic for a detailed description.

Bas
  • 26,772
  • 8
  • 53
  • 86
  • But how to do the solution of this problem ? because on rounding of this 0.0999999999 becomes 0.1 ans my control never go in condition if(distanceFactor==0) – Sss Jul 03 '14 at 09:20
  • thanks but please also let me know how to make the solution of problem in the current situation. – Sss Jul 03 '14 at 09:39
  • 2
    You should **not** do `if(distanceFactor==0)`, **period**. You should do something like this: `if(Math.Abs(distanceFactor-0) < 0.000001)` where `-0` can be removed, but `0` here is the original `0` from your original expression, so if you compare to something else, it goes there, and `0.000001` is a *small enough* value that will be enough to catch the values you're interested in. – Lasse V. Karlsen Jul 03 '14 at 10:31