1

Thank you for reading this.

A float in c# has a range of +- 3.4 * 10^38, a double 1.7 ^308 Consider the following program:

using System;

double nice;
float wow;
nice = 1.50* Math.Pow(10,300);
wow = (float) (nice);

Console.WriteLine(nice);
Console.WriteLine(wow);

output: 
1,5E+300
8

This got me really confused, how can such a large number be converted to 8 as a float? When we convert a double to a float, a float has mantissa length of 23 bits, exponent 8 bits a double 52 bits and 11. So when I convert explicitely from double to float and the number is that big, this means that the exponent part of the float that has only 8 bits, thus an overflow. Do the other 3 bits just in case of such a large number "just get slid off" or what happens?

Also when I do the same thing for an (int) it also gives me a very weird response.

Can anyone explain me why this is the response I get and when happens when the exponent part of a double is too big to fit in the one of the float?

kenshieva
  • 101
  • 6
  • 3
    The value of `wow` is `Infinity`. `wow.ToString()` produces `∞`. I suspect `Console.WriteLine()` is doing the best it can... – Jay Buckman Aug 02 '22 at 18:45
  • 1
    Does this answer your question? [Why is infinity printed as "8" in the Windows 10 console?](https://stackoverflow.com/questions/40907417/why-is-infinity-printed-as-8-in-the-windows-10-console) – Markus Safar Aug 02 '22 at 18:51

1 Answers1

2

It isn't converted to 8 (eight). It's converted to infinity, whose representation () looks like a sideways eight. It's possible that whatever environment you're viewing your output in displays this like an 8 due to font or culture settings.

Specifically, it's PositiveInfinity, whose docs clarify:

This constant is returned when the result of an operation is greater than MaxValue.

StriplingWarrior
  • 151,543
  • 27
  • 246
  • 315