Versions Compared

Key

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

...

Also, see EXP08-J. Be aware of integer promotions in binary operators.

Noncompliant Code Example

In this noncompliant example, an int is converted to float. Because a floating point number cannot be precise to 9 digits, the result of subtracting the original from this value is non-zero.

Code Block
bgColor#FFcccc
class WideSample {
  public static void main(String[] args) {
    int big = 1234567890;
    float approx = big;
    System.out.println(big - (int)approx);  // this is expected to be zero but it prints -46
  }
}

Compliant Solution

The significand part of a floating point number can hold at most 23 bit values. Anything above this threshold is discarded due to precision loss, as is demonstrated in this compliant solution.

Code Block
bgColor#ccccff
class WideSample {
  public static void main(String[] args) {
    int big = 1234567890;
                
    float approx = big;
    if(Integer.highestOneBit(big) <= Math.pow(2, 23)) { //the significand can store at most 23 bits
      System.out.println(big - (int)approx);  //always prints zero now
    }
    else {
      //handle error
      throw new ArithmeticException("Insufficient precision");
    }
  }
}

Risk Assessment

Casting numeric types to wider floating-point types may lose information.

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

INT33-J

low

unlikely

medium

P2

L3

Automated Detection

TODO

Related Vulnerabilities

Search for vulnerabilities resulting from the violation of this rule on the CERT website.

Other Languages

This rule appears in the C Secure Coding Standard as FLP36-C. Beware of precision loss when converting integral types to floating point.

This rule appears in the C++ Secure Coding Standard as FLP36-CPP. Beware of precision loss when converting integral types to floating point.

References

Wiki Markup
\[[JLS 05|AA. Java References#JLS 05]\] Section [5.1.2, Widening Primitive Conversion|http://java.sun.com/docs/books/jls/third_edition/html/conversions.html#5.1.2]

...