...
In this noncompliant code example, the division and multiplication operations are performed on integral values; the results of these operations are then converted to floating point. :
| Code Block | ||
|---|---|---|
| ||
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 |
...
This compliant solution eliminates the truncation and overflow errors by storing the integers in the floating-point variables before performing the arithmetic operations.:
| Code Block | ||
|---|---|---|
| ||
short a = 533; int b = 6789; long c = 4664382371590123456L; float d = a; double e = b; double f = c; d /= 7; // d is 76.14286 e /= 30; // e is 226.3 f *= 2; // f is 9.328764743180247E18 |
...
This noncompliant code example attempts 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.
...
As a consequence of Java's numeric promotion rules, the division operation performed is an integer division whose result is truncated to 1. This result is then promoted to double before being passed to the Math.ceil function.
...
This compliant solution casts the divisor to double before the division is performed. .:
| Code Block | ||
|---|---|---|
| ||
int a = 60070; int b = 57750; double value = Math.ceil(a/((double) b)); |
Consequently, the numerator is automatically promoted to double. The division operation becomes a double divide, and value is assigned the correct result. As in the previous compliant solution, this practice ensures that at least one of the operands of each operation is a floating-point number
...