-1

I assign 2097151.3 to the float variable and the application prints only the integer part. Possible bug?

public static void Main(string[] args)
{
    float foo = 2097151.3F;

    Console.WriteLine(foo); // prints 2097151

    Console.ReadKey();
}

I'm running a .NET Core console application.

Screenshot

Manfred Radlwimmer
  • 13,257
  • 13
  • 53
  • 62
Joe
  • 1
  • 1
  • 1
    See precision specs at https://msdn.microsoft.com/en-us/library/b1e65aza.aspx - only 7 digits – rbm Nov 11 '16 at 13:37
  • 1
    Possible duplicate of [Is floating point math broken?](http://stackoverflow.com/questions/588004/is-floating-point-math-broken) – MakePeaceGreatAgain Nov 11 '16 at 13:41

1 Answers1

2

Nope. Floating point numbers have been around since the 1940s. A float is only really good for 7 significant figures.

The nearest float to 2097151.3 is 2097151.25, and WriteLine is clever enough to know that and so it truncates accordingly.

If you want precise decimal values then use a decimal type.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
  • So the question is why does `WriteLine` truncate the value, if i´s actually `2097151.25`. – MakePeaceGreatAgain Nov 11 '16 at 13:43
  • @HimBromBeere: Because the "joke" digits are irrelevant and C# is being sensible. You *can* tweak the fomatter to yield all the digits if you must. – Bathsheba Nov 11 '16 at 13:44
  • If a float (my float was 2097151.3) only can store 7 digits (2097151), why are you speaking about 2097151.25? – Joe Nov 11 '16 at 13:50
  • @Joe Because "7 digits" is only an approximation of what's going on. Floats can store up to 24 *binary* digits (technically 23, but there's an implicit one you get essentially for free in many cases), which works out to approximately 7 *decimal* digits. – Kyle Nov 11 '16 at 14:39