The code here is straight forward but I don't understand the results:
float percent = 0.69f;
int firstInt = (int)(percent*100f);
float tempFloat = percent*100f;
int secondInt = (int)tempFloat;
Debug.Log(firstInt + " " + secondInt);
Why is firstInt
68 but secondInt
is 69?
It looks like the compiler has figured out the value of the
percent*100f
expression using double math, and optimized away the computation. This is not allowed when intermediate results are saved in a float variable.
Since .69 does not have anexact representation in float or in double, the two representations "land" on different sides of an int: double is slightly above, while float is slightly below the actual value of .69.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With