Java Reference
In-Depth Information
c
is rounded to the nearest value that can be represented by type
double
, and the com-
puted value of
f
(9.328764743180247E18) differs from the exact mathematical result
(9328564743180246912). This loss of precision is one of the many reasons correct pro-
gramming of expressions that mix integer and floating-point operations or values requires
careful consideration. See “
NUM13-J. Avoid loss of precision when converting primitive
integers to floating-point
”
[Long 2012], for more information about integer-to-floating-
pointconversion.Evenwiththislossofprecision,however,thecomputedvalueof
f
isfar
more accurate than that produced in the noncompliant code example.
Noncompliant Code Example
This noncompliant code example attempts to compute the whole number greater than the
ratio of two integers. The result of the computation is 1.0 rather than the intended 2.0.
int a = 60070;
int b = 57750;
double value = Math.ceil(a/b);
Asaconsequence ofJava'snumeric promotion rules,thedivision operation performed
isan
integer
divisionwhoseresultistruncatedto1.Thisresultisthenpromotedto
double
before being passed to the
Math.ceil()
method.
Compliant Solution
This compliant solution casts one of the operands to
double
before the division is per-
formed.
int a = 60070;
int b = 57750;
double value = Math.ceil(a/((double) b));
As a result of the cast, the other operand is automatically promoted to double. The di-
vision operation becomes a double divide, and
value
is assigned the correct result of 2.0.
As in previous compliant solutions, this practice ensures that at least one of the operands
of each operation is a floating-point number.