-1

I have this code:

static void Main()
{
    float i;

    for (i = 0; i <= 100; i = i + 0.01F)
    {
        Console.WriteLine(i);

    }

}

And it prints me this:

0
0.01
0.02
0.03
0.04
0.05
0.05999999
0.06999999
0.07999999
0.08999999
0.09999999
0.11

Is this a bug or am I doing something wrong? Is there any solution to this?

  • 1
    http://csharpindepth.com/Articles/General/FloatingPoint.aspx – Tim Schmelter Jul 21 '14 at 07:24
  • 3
    [What Every Computer Scientist Should Know About Floating-Point Arithmetic](http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html) – Steve Jul 21 '14 at 07:24
  • 1
    There are numerous duplicates on [SO] that explain the behavior of floating point values in C# and other languages, I picked one of them that I thought explained the problem nicely, if you require other explanations/examples, please do a search for [float bug .NET](http://stackoverflow.com/search?q=float+bug+%5B.net%5D) – Lasse V. Karlsen Jul 21 '14 at 07:26

1 Answers1

6

It is not a bug. This is a fundamental property of floating point numbers. The numbers are stored as a mantissa and an exponent and they cannot represent every number possible with perfect precision. If you need precision, you have to use decimal types.

For a lot of information about this see What Every Computer Scientist Should Know About Floating-Point Arithmetic

Sami Kuhmonen
  • 30,146
  • 9
  • 61
  • 74