- Home /
(int)(variable*float ) problem?
Hi, I am really confused:
float deneme = 100f; // or int deneme=100
int a = (int)(deneme * 0.01f);
int b = (int)(100 * 0.01f);
Why both gives different results? a=0; b=1;
Answer by meat5000 · May 04, 2016 at 02:18 PM
Floating Point error.
On my machine with your snippet I get
float deneme = 100.00001f; //a = 1;
float deneme = 100.000001f; // a = 0;
An int will Never round up. Only down.
But why using avariable and 100 gives different results?
Different execution order? Different intermediate results? Hard to say without seeing what IL the two versions compile down to.
What Every Computer Scientist Should $$anonymous$$now About Floating-Point Arithmetic.
Also, $$anonymous$$athf.RoundToInt will take care of your issue.
sorry i dont get it. Lets forget deneme is float.
int deneme=100; int a = (int)(deneme 0.01f); int b = (int)(100 0.01f);
now a =0 and b=1 again. why this is floating Point error?
Read the link I provided.
When you do int b = (int)(100f * 0.01f)
think about the intermediate result. 100f * 0.01f
is likely giving you something like 0.9999999998. When you type cast that to an int it truncates everything past the decimal point, so you get 0. For whatever reason (as I stated earlier), when doing the same with a variable it's executing the floating point operations slightly differently so deneme * 0.01f
might be giving you exactly 1 or 1.000000001 or something. And again, when you cast that to int it's truncating everything past the decimal point, leaving you with 1.
The reason for the "not exact" numbers is explained in my link above. And as the title explains it is information you should know about.
Use $$anonymous$$athf.RoundToInt(deneme * 0.01f)
ins$$anonymous$$d of typecasting to int and your problem will cease to be.