Converting Float to Long gives negative value
Why does the conversion return the expression -ve?
float f = long.MaxValue;
Console.WriteLine("long to float: {0}",f);
Console.WriteLine("long Max: {0}",long.MaxValue);
Console.WriteLine("float to long casting: {0}",(long)f);
//Console.WriteLine("converting float to long: {0}",Convert.ToInt64(f));
//Above statement gives OverflowExection as expected.
OUTPUT:
long to float: 9.223372E+18
long Max: 9223372036854775807
float to long casting: -9223372036854775808
Again, long.MinValue
gives the correct result.
+3
source to share
1 answer
As M. Kazem pointed out in a comment, this led to an overflow, and according to the C # spec compiler, it silently ignored it
Console.WriteLine("float to long casting: {0}",(long)f);
But if we convert above under the test, an overflow expression is issued.
checked
{
Console.WriteLine("float to long casting: {0}",(long)f);
}
0
source to share