Click here to Skip to main content
15,895,777 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
(int)(0.04F*100F) = 3 ????? WHY?
Posted

It appears that using a float type induces less precision, and when the resulting value is cast to an int, it rounds down to the nearest whole number. Note the following:

float y = 0.04F * 100F; // 4 - without casting DURING the math operation, it's fine.
int x = (int)y); // 4 - and then it casts without issue

int x = (int)(0.04F * 100F); // 3 - if you cast during the operation, it's just plain wrong

int x = Convert.ToInt32(0.04F * 100F); // 4 - using ConvertTo results in the expect answer, even if you put the expression in as the parameter (probably because the expression is evaluated before passing it to the ToInt32() method.

int x = (int)(0.04 * 100); // 4 - implicit doubles

int x = (int)(0.04M * 100M); // 4 - using decimal for the math - much more precise

int x = (int) 0.04D * 100D); // 4 - doubles seem to act fine

Welcome to the wonderful world of floating point math.
 
Share this answer
 
v2
Because you can lose precision between floating and integers. Floating point numbers are designed to handle calculations involving very large or very small numbers, but there is a cost in that precision will be lost - how much depends on the actual values. If you want precise answers to your calculations then you should always use integral values.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900