-1

C# code:

double value = float.MaxValue;
Console.WriteLine(value / 2);

give different values (C# gives 1.70141173319264E+38 and C# without floats gives me 1.701411735e+38) me .

When I use the c# code:

double value = 3.40282347E+38;
Console.WriteLine(value / 2);

I get the same as floats. Is MSDN wrong?

Dot Net Fiddle
float.MaxValue is 3.40282347E+38.
Float MaxValue

trinalbadger587
  • 1,905
  • 1
  • 18
  • 36
  • 6
    *JavaSccript/C# without floats gives me* ... what? – Pointy Apr 18 '16 at 16:43
  • 3
    IMO just remove `javascript` entirely and ask why `double value = float.MaxValue / 2` is different than `double value = 3.40282347E+38 / 2`. – Quantic Apr 18 '16 at 16:45

1 Answers1

2

Fiddling around I found that Console.WriteLine(((3.40282347E+38 / 2) == (float.MaxValue / 2)).ToString()); prints False while Console.WriteLine(((3.40282347E+38f / 2) == (float.MaxValue / 2)).ToString()); prints True. It's because the language does this:

By default, a real numeric literal on the right side of the assignment operator is treated as double.

Your number is a double and you are comparing it against a float, so the precision is different by default. You have to force the number to be a float by adding f on the end of it.

Quantic
  • 1,779
  • 19
  • 30
  • `float.MaxValue - 3.40282347E+38F` = 0 – stuartd Apr 18 '16 at 16:53
  • Is the extra precision on the double, false precision (or does float.MaxValue have more precision than floats? – trinalbadger587 Apr 18 '16 at 16:55
  • `float` is an alias for `Single`. `double` is `Double`'s alias. It's quite literally about twice as much precision. – Jeroen Vannevel Apr 18 '16 at 16:57
  • How can float.MaxValue's precision be more than a floats, then a float can't store it? – trinalbadger587 Apr 18 '16 at 16:58
  • 1
    @trinalbadger587 It's not. You are implicitly casting the `float` to a `double`: `double value = float.MaxValue`, which is adding a bunch of digits (the specifics of which I would have to research, e.g., read the discussion under the answer [here](http://stackoverflow.com/questions/1421520/formatting-doubles-for-output-in-c-sharp)). `float value = float.MaxValue` is a different precision and ends up being a different number than `double value = float.MaxValue` – Quantic Apr 18 '16 at 17:04
  • 1
    @trinalbadger587 And to be clear, yes, I *think* the "extra precision on the double is false precision". Casting `float.MaxValue` from its float precision to a double will add digits, but you didn't not gain any precision from the original `float` number. The extra digits are not necessarily incorrect as long as they fall inside of the "interval" of double precision datatype. Again, this level of detail is beyond my on-the-spot understanding of the datatypes, which is why I suggested reading the other thread (or better yet get a book on the subject). – Quantic Apr 18 '16 at 17:15