settingsAccountsettings
Menusettings

Q: Why the sum of 0.1+0.1+0.1... (1000 times) is NOT 100 in C#?

+4 votes

Why is that 0.1+0.1+0.1+0.1... (1000 times) is NOT 100 as a result in C#, but instead I am getting 99.99905?

asked in C# category by user eiorgert
edited by user golearnweb

1 Answer

+2 votes
 
Best answer

It depends on wha tyou are using - if you are using float as a numerical data representation you will get the number mentioned above;

However - you also have double and decimal... Here is my code (with float, double and decimal) - and I am having 100 as a result! :-) Test it yourself!

using System;

class ZeroPointOne
{
    static void Main()
    {
        float sumfloat = 0f;
        for (int i = 0; i < 1000; i++)
        {
            sumfloat = sumfloat + 0.1f;
        }
        Console.WriteLine("Sum Float = {0}", sumfloat);

        /////////////////////////////////////////

        double sumdouble = 0d;
        for (int i = 0; i < 1000; i++)
        {
            sumdouble = sumdouble + 0.1d;
        }
        Console.WriteLine("Sum Double = {0}", sumdouble);

        /////////////////////////////////////////

        decimal sumdecimal = 0m;
        for (int i = 0; i < 1000; i++)
        {
            sumdecimal = sumdecimal + 0.1m;
        }
        Console.WriteLine("Sum Decimal = {0}", sumdecimal);
    }
}


 

answered by user hues
edited by user golearnweb
...