1
static void Main(string[] args)
{
           double y = 23.12F;
           Console.WriteLine(y);
           Console.Read();
}

why value of y shows 23.1200008392334 instead of 23.12

static void Main(string[] args)
    {
        int i = -9; uint j = (uint)i;
        Console.WriteLine(j);
        Console.Read();
    }

How j shows value 4294967287

mskfisher
  • 3,291
  • 4
  • 35
  • 48
G K
  • 11
  • 2
  • 2
    Your second example seems very strange. Your are converting a negative number in a type that does not support negative number – meziantou Sep 20 '11 at 08:11
  • 2
    The [two's complement](http://en.wikipedia.org/wiki/Two's_complement) of -9 is: 1111 1111 1111 1111 1111 1111 1111 0111. Take this number into a calculator that can convert binary into decimal and you get 4294967287 ;p – Em1 Sep 20 '11 at 08:21

2 Answers2

7

Floating points are only guaranteed to be exact for integer values; beyond that, they cannot represent all numbers; 23.1200008392334 is the closest it can get to 23.12, due to how IEEE754 works.

If you want "typical" handing of decimal values... use decimal instead:

decimal y = 23.12M;

With the uint - because uint doesn't have negative values. Instead, you are tracking backwards from the maximum value of uint. If you don't want this, use checked:

uint j = checked((uint) i);

or

checked
{
    uint j = (uint)i;
}

then it will explode in a shower of sparks instead. Sometimes a good thing; sometimes bad. unchecked is the default.

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
1

According to MSDN 'that's just how double works' http://social.msdn.microsoft.com/forums/en-US/csharpgeneral/thread/1fcf6486-807d-4dce-8aef-7fe5268b568d/

I know that this is Java, but very similar to C# : Convert float to double without losing precision

Community
  • 1
  • 1
JP Hellemons
  • 5,977
  • 11
  • 63
  • 128