0

Possible Duplicates:
Why is (double)0.6f > (double)(6/10f)?
Why is floating point arithmetic in C# imprecise?

I have the following code in C#:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace StackOverflow
{
    class Program
    {
        static void Main(string[] args)
        {
            float num1 = 17.03F;
            float num2 = 17F;
            float result = num1 - num2;
            Console.WriteLine(result);
        }
    }
}

The code works fine but I am not getting the expected result. Can someone explain why this is happening?

Community
  • 1
  • 1
santosh singh
  • 27,666
  • 26
  • 83
  • 129

4 Answers4

4

I guess you are refering to deviations cause by Floating point arithmetics. You can read about in in the provided link.

If you really need to make the calculation 100% accurate, you can use decimal instead of float.

Øyvind Bråthen
  • 59,338
  • 27
  • 124
  • 151
1

Because you are using float. Float is an extremely approximate value. Always use it with an Epsilon (maximum error allowance) when comparing.

I am guessing you are getting result = 0.02999999?

Alex
  • 14,338
  • 5
  • 41
  • 59
1

Floating point maths is likely to contain rounding approximations, see the many duplicate questions on this site, or read here:

http://en.wikipedia.org/wiki/Floating_point

Paddy
  • 33,309
  • 15
  • 79
  • 114
1

What about this? : What Every Computer Scientist Should Know About Floating-Point Arithmetic

alanc
  • 4,102
  • 21
  • 24
alpha-mouse
  • 4,953
  • 24
  • 36