-1

I'm really confused. My code:

        Console.WriteLine(myChanges + " TEN METHOD " +  (ten_num * TEN));(This for debug)
        if ((myChanges - (ten_num * TEN)) >= 0)
        {

        }else
            print error message

Like myChannges = 0.3 ; TEN = 0.1; ten_num = 3, but when I print (myChanges - (ten_num * TEN)) it equals 5.4411512312578E-17

Why not 0? Any solutions?

aschipfl
  • 31,767
  • 12
  • 51
  • 89

2 Answers2

11

This is due to the rounding errors inherent to floating point operations. See http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html for details.

Tarik
  • 10,206
  • 1
  • 20
  • 37
1

As has already been answered, floats/doubles have rounding errors. To get around this you could consider using BigDecimal objects or BigInteger objects. They are slower but much more accurate. Plus they can basically hold as many digits as you please.

Connor
  • 662
  • 3
  • 9
  • 29