Versions Compared

Key

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

The following 19 specific conversions on primitive types are called the widening primitive conversions:

  • byte to short, int, long, float, or double
  • short to int, long, float, or double
  • char to int, long, float, or double
  • int to long, float, or double
  • long to float or double
  • float to double

Conversion from int or long to float or from long to double can lead to loss of precision (loss of least significant bits). In these cases, the resulting floating-point value is a rounded version of the integer value, using IEEE 754 round-to-nearest mode. Despite this loss of precision, The Java Language Specification (JLS) requires that the conversion and rounding occur silently, that is, without any runtime exception (see the JLS, §5Narrower primitive types can be cast to wider types without affecting the magnitude of numeric values. However, when the expressions are not strictfp (guideline FLP04-J. Use the strictfp modifier for floating point calculation consistency), conversions from float to double may lose information about the overall magnitude of the converted value. See JLS Section 5.1.2, "Widening Primitive Conversion" [JLS 2015], for more information.Conversion from ). Conversions from integral types smaller than int to a floating-point type and conversions from int to double can never result in a loss of precision. Consequently, programs must ensure that conversions from an int or long to float, or a floating-point type or from long to double can lead to do not result in a loss of required precision (loss of least significant bits). No runtime exception occurs despite this loss. Also, see guideline EXP05-J. Be aware of integer promotions in binary operators.

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

Noncompliant Code Example

In this noncompliant code example, two identical large integer literals are passed as arguments to the subFloatFromInt() method. The second argument is coerced to float, cast back to int, and subtracted from 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 non-zero. The result is returned as a value of type int.

This method could have unexpected results because of the loss of precision. In FP-strict mode, values of type float have 23 mantissa bits, a sign bit, and an 8-bit exponent (see NUM53-J. Use the strictfp modifier for floating-point calculation consistency across platforms for more information about FP-strict mode). The exponent allows type float to represent a larger range than that of type int. However, the 23-bit mantissa means that float supports exact representation only of integers whose representation fits within 23 bits; float supports only approximate representation of integers outside that range.

Code Block
bgColor#FFcccc

strictfp class WideSample {
  public static voidint main(String[] argssubFloatFromInt(int op1, float op2) {
    intreturn bigop1 = 1234567890- (int)op2;
  }

  float approx = big;public static void main(String[] args) {
    System.out.println(big - (int)approx);   int result = subFloatFromInt(1234567890, 1234567890);
    // This is expected to prints -46, not 0, as may be zeroexpected
   but it prints -46 System.out.println(result);  
  }
}

Note that conversions from long to either float or double can lead to similar loss of precision.

Compliant Solution

...

(ArithmeticException)

This compliant solution range checks the argument of the integer argument (op1) to ensure it can be represented as a value of type float without a loss of precision: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

strictfp class WideSample {
  public static voidint main(String[] args) {subFloatFromInt(int op1, float op2)
    int big = 1234567890;
             throws ArithmeticException    {

    // The significand can store at most 23 bits
    if ((bigop2 > 0x007fffff) || (bigop2 < -0x800000)) { 
      throw new ArithmeticException("Insufficient precision");	
    }

     float approx = bigreturn op1 - (int)op2;
  }

  public static void main(String[] args) {
    int result = subFloatFromInt(1234567890, 1234567890);
    System.out.println(big(result);  
  }
}

In this example, the subFloatFromInt() method throws ArithmeticException. This general approach, with appropriate range checks, can be used for conversions from long to either float or double.

Compliant Solution (Wider Type)

This compliant solution accepts an argument of type double instead of an argument of type float. In FP-strict mode, values of type double have 52 mantissa bits, a sign bit, and an 11-bit exponent. Integer values of type int and narrower can be converted to double without a loss of precision.

Code Block
bgColor#ccccff
strictfp class WideSample {
  public static int subDoubleFromInt(int op1, double op2) {
    return op1 - (int)approx);  // Prints zero when no precision is lost)op2;
  }

  public static void main(String[] args) {
    int result = subDoubleFromInt(1234567890, 1234567890);
    // Works as expected
    System.out.println(result);  
  }

}

Note that this compliant solution cannot be used when the primitive integers are of type long because Java lacks a primitive floating-point type whose mantissa can represent the full range of a long.

Exceptions

NUM13-J-EX0: Conversion from integral types to floating-point types without a range check is permitted when suitable numerical analysis demonstrates that the loss of the least significant bits of precision is acceptable.

Risk Assessment

Casting Converting integer values to floating-point types whose mantissa has fewer bits than does the original integer value will lose precision. In the absence of strictfp, casts from type float to type double may also lose precision.can result in a rounding error.

Rule

Guideline

Severity

Likelihood

Remediation Cost

Priority

Level

INT03

NUM13-J

low

Low

unlikely

Unlikely

medium

Medium

P2

L3

Automated Detection

Automatic detection of casts that may can lose precision is straightforward.

Related Vulnerabilities

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

Other Languages

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

This guideline appears in the C++ Secure Coding Standard as 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, Widening Primitive Conversion|http://java.sun.com/docs/books/jls/third_edition/html/conversions.html#5.1.2]

Sound determination of whether those casts correctly reflect the intent of the programmer is infeasible in the general case. Heuristic warnings could be useful.

ToolVersionCheckerDescription
CodeSonar
Include Page
CodeSonar_V
CodeSonar_V

JAVA.CAST.FTRUNC

Cast: Integer to Floating Point (Java)

Parasoft Jtest
Include Page
Parasoft_V
Parasoft_V
CERT.NUM13.AICAvoid implicit casts from integer data types to floating point data types
PVS-Studio

Include Page
PVS-Studio_V
PVS-Studio_V

V6011

Related Guidelines

Bibliography


...

Image Added Image Added Image AddedINT02-J. Remember that the remainder operator may return a negative result value      06. Integers (INT)      INT04-J. Do not attempt to store signed values in the char integral type