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.*

Recommended Answers

All 3 Replies

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.

commented: Lucid and to the point! Thanks a lot! +1

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.