简体   繁体   中英

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?

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?

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM