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?

5
  • 1
    What do you expect? What do you get? Commented Nov 11, 2010 at 9:20
  • 1
    Your expectations of floating point arithmetic are incorrect. See the question linked from the comment above, or any number of other questions tagged floating-point. Also see csharpindepth.com/Articles/General/FloatingPoint.aspx Commented Nov 11, 2010 at 9:22
  • What result are you expecting and what result are you getting? Commented Nov 11, 2010 at 9:22
  • 1
    @Jon, both questions have the wrong names, thus - low search relevance. Commented Nov 11, 2010 at 9:23
  • Expected result should be 0.03 but i am getting 0.03000069 Commented Nov 11, 2010 at 9:32

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

Comments

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?

Comments

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

Comments

1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.