Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C# double to float conversion issue

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading