Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Noncompliant Code Example

In this 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. The results of the integral operations are truncated to the nearest integer and can also overflow. As a result, the floating-point variables de, and f are initialized incorrectly because the truncation and overflow take place before the conversion to floating point.example—extracted from a real program—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, 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.  

Code Block
bgColor#FFCCCC
shortint a = 53360070;
int b = 678957750;
long c = 4664382371590123456L;

float d
double value = Math.ceil(a / 7;    // d is 76.0 (truncated)
double e = b / 30;  // e is 226.0 (truncated)
double f = c * 2;   // f is -9.1179793305293046E18 due to integer overflowb);

Compliant Solution

This compliant solution casts the divisor to double before the division is performed. 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.

Code Block
bgColor#CCCCFF
int a = 60070;
int b = 57750;

double value = Math.ceil(a/((double) b));

Applicability

Improper conversions between integers and floating-point values can yield unexpected results, especially from precision loss. In some cases, these unexpected results can involve overflow or undefined behavior.

...