Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Casting Results of Float Multiplication Produces Differing Results if the Float is First Saved to a Variable? [duplicate]

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?

like image 669
Foggzie Avatar asked Aug 08 '16 22:08

Foggzie


1 Answers

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.

like image 99
Sergey Kalinichenko Avatar answered Sep 23 '22 20:09

Sergey Kalinichenko