Since casting a
double
value to
int
throws away mathematical precision it might seem that weβd rarely want to do that. But we can use truncation, with a bit of arithmetic, to round
double
values to the nearest
int
value by adding or subtracting 0.5 and then casting the result with
(int)
:
For example, if we divide
7.0 / 4.0
we get
1.75
. And if we cast that to an
int
, it would be truncated to
1
. But if we want to round it to the nearest
int
, rather than truncating it, adding
0.5
will produce a number that is greater than
2.0
and thus will get truncated to
2
. Assuming weβre okay rounding above the next integer value if the decimal part is greater than
0.5
, as it is here. Then casting
that value to an
int
will truncate down. So in this case
1.75 + 0.5
gives us
2.25
which is then truncated to
2
. On the other hand adding
0.5
to the result of evaluating
5.0 / 4.2
, namely
1.25
, only gets us to
1.75
which truncates back to
1
which is the nearest integer to
1.25
.
And notice that here we need to parenthesize the expression
number + 0.5
so that it is evaluated first and then the result cast to a
double
. Without the parentheses, the cast to
int
would convert
number
to an
int
first because of the higher precedence of casting than division, and then that truncated
int
value would be infected by the
0.5
giving us a double result with a fractional part of
0.5
.