assume latgeInt=2147483647
Debug.Log(largeInt); //2147483647
 float largeFloat = largeInt;
 Debug.Log(largeFloat); ///2.147484E+09
 int backAgain = (int)largeFloat;
 Debug.Log(backAgain);  //-2147483648 *This part i did not get. 

I assume there was some data loss when float was explicitly casted into int .
But the loss should be in right most digits.
How come sign got changed !
Please explain me .
Thanks in advance.*

Edited by Dani: Formatting fixed

1 Year
Discussion Span
Last Post by sandeepjkl

2147483647 is the largest number that an int can store. When you convert it to float, it becomes 2147483648.0 due to floating point accuracies. When you convert that back to int, you'd get 2147483648, except that that's too large to fit into an int. So instead you get an overflow, resulting in -2147483648, which is the smallest number an int can store - and thus the first number you get after an overflow.

If you used a long instead of an int for backAgain, it would have the value 2147483648 as (possibly) expected.

I assume there was some data loss when float was explicitly casted into int .

There was a loss of precision when the int was casted to float (note that this cast can be lossy even though it is implicit - this may perhaps be considered improper language design). There was then additionaly an overflow when casting back.

Edited by sepp2k

Votes + Comments
Lucid and to the point! Thanks a lot!

The explicts keyword declares a user-defined type conversion operator that must be invoked with a cast.Explict casts are used when a vale is reduced to few bytes.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.