CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 7 of 7
  1. #1
    Join Date
    May 2002
    Location
    Ukraine
    Posts
    228

    Talking Surprise! 0.77 * 100 == 76

    Try the code:

    float a = 0.77F;
    int b = (int)(100 * a);
    Console.WriteLine(b.ToString());

    Result is 76.

    What do you think about such strange .Net calculate execution ?

  2. #2
    Join Date
    Dec 2003
    Location
    http://map.search.ch/zuerich.en.html
    Posts
    1,074

    Re: Surprise! 0.77 * 100 == 76

    Nothing new! FAQ
    Useful? Then click on (Rate This Post) at the top of this post.

  3. #3
    Join Date
    Mar 2006
    Posts
    7

    Re: Surprise! 0.77 * 100 == 76

    simple solution

    Code:
    decimal a = 0.77M;
    int b = (int)(100 * a);
    Console.WriteLine(b.ToString());

  4. #4
    Join Date
    Oct 2005
    Location
    Islamabad, Pakistan
    Posts
    1,277

    Re: Surprise! 0.77 * 100 == 76

    can also do it with float
    Code:
                           float a = 0.77f;
    			int b =  Convert.ToInt32(100 * a);
    			console.WriteLine(b.ToString());

  5. #5
    Join Date
    May 2002
    Location
    Ukraine
    Posts
    228

    Re: Surprise! 0.77 * 100 == 76

    Quote Originally Posted by Syrix
    simple solution

    Code:
    decimal a = 0.77M;
    int b = (int)(100 * a);
    Console.WriteLine(b.ToString());
    Solution is not the problem.
    I used Round, for example.
    When I met the problem I was suppressed by so non-clear behavior of the code.
    I always used double before.
    Float was returned as object from DataRow element from correspond DB Field:-)
    And I do not understand, why 100*0.77f == 76.99999…
    Is it Microsoft or Intel?

  6. #6
    Join Date
    Mar 2006
    Posts
    7

    Re: Surprise! 0.77 * 100 == 76

    Quote Originally Posted by Alex Rest
    And I do not understand, why 100*0.77f == 76.99999…
    Is it Microsoft or Intel?
    it is because of the processor can never represent exactly 0.77 in binary.

  7. #7
    Join Date
    Dec 2003
    Location
    http://map.search.ch/zuerich.en.html
    Posts
    1,074

    Re: Surprise! 0.77 * 100 == 76

    Quote Originally Posted by Alex Rest
    And I do not understand, why 100*0.77f == 76.99999…
    That's why I posted the FAQ...
    Useful? Then click on (Rate This Post) at the top of this post.

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