Reputation: 77
How are float results rounded to integer ones when converting from float to int?
Sometimes I made some complex arithmetic operation (which comprises multiplications, divisions etc) between integer variables and convert the result again to int.
Example:
result = (int) ((int1 + int2) * int3 / int4);
It happens that sometimes the result is rounded to the nearest integer, other times to the lower integer even if the float result is nearer to the upper one, sometimes instead the result is rounded by 2 integer numbers up or down (i.e. if the result is -150.69 it can happen that result = -149).
There is some law in conversions from float to int or it depends on the case?
Thanks in advance.
Example:
int1 = 31;
int2 = -1366;
int3 = 50;
int4 = 1000;
result should be -66.75 but the returned one is -65.
Upvotes: 0
Views: 280
Reputation: 215193
In your code, unless int1
through int4
are actually floats, you don't have any floating point types, so your question is irrelevant to your code.
As for the question itself, floating point to integer conversion always takes place by truncation (discarding the fractional portion). For rounding, the standard library has a number of functions like floor
, ceil
, round
, etc. that can perform different types of rounding.
Upvotes: 1