CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3
  1. #1
    Join Date
    Jul 2002
    Posts
    788

    what is the double value of 0.1+0.1+0.1?

    in CSharp,

    Code:
      double d = 0.10 + 0.10 + 0.10;
    //d=0.30000000000000004;
    why??

  2. #2
    Join Date
    Jul 2006
    Posts
    297

    Re: what is the double value of 0.1+0.1+0.1?

    A double is a 64bit value encoded in base 2 format, or binary. Some numbers, like .10 do not have a binary representation so a rough approximation must be used and will not be 100% accurate. I believe it has a error of around 3% though I could be wrong.

    If you want precision use decimal. Decimal is a 128bit value encoded in base 10 format, or decimal. This can store any decimal number and you will not loose precision with a value such as .10.

    Precision aside, calculations using doubles are quicker because they are base 2 and the computer understands this better than base 10. Doubles also have a much wider range of possible values and take up less storage space. Most math done in applications will work fine with doubles, but once you start dealing with financial applications or anything that really needs the precision you need to use decimals.

  3. #3
    Join Date
    May 2007
    Posts
    1,546

    Re: what is the double value of 0.1+0.1+0.1?

    Just to expand on the above post - this isn't a C# issue, it's just something you have to live with when using floating point math. It's just how floats and doubles work. This is why you should never compare doubles using "==", you should always do something like:

    Code:
    double epsilon = 0.0001;
    double val1 = 0.1 + 0.1 + 0.1;
    
    if (Math.Abs (val1 - 0.3) < epsilon)
        Console.WriteLine ("values are the same");
    else
        Console.WriteLine ("Values are not the same");
    Of course, the value of 'epsilon' that you choose is up to you. If this isn't good enough, then you shouldn't use floats/doubles.
    www.monotorrent.com For all your .NET bittorrent needs

    NOTE: My code snippets are just snippets. They demonstrate an idea which can be adapted by you to solve your problem. They are not 100% complete and fully functional solutions equipped with error handling.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured