Versions Compared

Key

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

...

Note that conversions from float to double can also lose information about the overall magnitude of the converted value. (See guideline FLP04-J. Use the strictfp modifier for floating point calculation consistency for additional information.)

Noncompliant Code Example

In this noncompliant code example, a value of type int is converted to the type float. Because type float has only 23 mantissa bits, the result of subtracting the original from this value is -46, not zero.

Code Block
bgColor#FFcccc
class WideSample {
  public static void main(String[] args) {
    int big = 1234567890;
    float approx = big;

    // This is expected to be zero but it prints -46
    System.out.println(big - (int)approx);  
  }
}

Compliant Solution

Numbers of type float have 23 mantissa bits, a sign bit, and an 8 bit exponent. The exponent allows type float to represent a larger range than that of type int. Nevertheless, integers whose representation requires more than 23 bits can only be represented approximately by a float.

Code Block
bgColor#ccccff
class WideSample {
  public static void main(String[] args) {
    int big = 1234567890;
                  
    // The significand can store at most 23 bits
    if ((big > 0x007fffff) || (big < -0x800000)) { 
      throw new ArithmeticException("Insufficient precision");	
    }

    float approx = big;
    System.out.println(big - (int)approx);  // Prints zero when no precision is lost
  }
}

Risk Assessment

Casting integer values to floating-point types whose mantissa has fewer bits than the original integer value will lose precision.

Guideline

Severity

Likelihood

Remediation Cost

Priority

Level

FLP10-J

low

unlikely

medium

P2

L3

Automated Detection

Automatic detection of casts that can lose precision is straightforward. Sound determination of whether those casts correctly reflect the intent of the programmer is infeasible in the general case. Heuristic warnings could be useful.

Related Vulnerabilities

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

Related Guidelines

C Secure Coding Standard: FLP36-C. Beware of precision loss when converting integral types to floating point

C++ Secure Coding Standard: FLP36-CPP. Beware of precision loss when converting integral types to floating point

Bibliography

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

...