Java Reference
In-Depth Information
60. Convert integers to floating-point for floating-point operations
Incautious use of integer arithmetic to calculate a value for assignment to a floating-point
variablecanresultinlossofinformation.Forexample,integerarithmeticalwaysproduces
integral results, discarding information about any possible fractional remainder. Further-
more,therecanbelossofprecisionwhenconvertingintegerstofloating-pointvalues.See
loss of precision when converting primitive integers to floating-point
,
” for additional in-
formation. Correct programming of expressions that combine integer and floating-point
values requires careful consideration.
Operations that could suffer from integer overflow or loss of a fractional remainder
should be performed on floating-point values, rather than integral values.
Noncompliant Code Example
In this noncompliant code example, the division and multiplication operations are per-
formed on integral values; the results of these operations are then converted to floating-
point.
short a = 533;
int b = 6789;
long c = 4664382371590123456L;
float d = a / 7; // d is 76.0 (truncated)
double e = b / 30; // e is 226.0 (truncated)
double f = c * 2;
// f is -9.1179793305293046E18
// because of integer overflow
The results of the integral operations are truncated to the nearest integer and can also
overflow. As a result, the floating-point variables
d
,
e
, and
f
are initialized incorrectly be-
cause the truncation and overflow take place before the conversion to floating-point.
Notethatthecalculation for
c
alsoviolates“NUM00-J.Detectorpreventintegerover-
flow” [Long 2012].