JavaScript is not currently enabled, but is required for full CodeSonar manual search and browse functionality.

If you are viewing this file in your hub's Web GUI, enable JavaScript in your browser: you will also need it for GUI functionality.

If you opened this file directly from disk, your browser may be directly suppressing JavaScript functionality: certain browsers perform this suppression on local files (but not files delivered by web servers) for security reasons.

CodeSonar® 9.2p0 CONFIDENTIAL CodeSecure Inc
Java


JAVA.CAST.FTRUNC : Cast: Integer to Floating Point (Java)

Summary

The result of an integral computation that might lose precision is cast into a floating point value.

Floating point operations are by nature approximated. This can introduce bugs when precise, mathematical properties are expected from inherently imprecise floating point computations. Moreover, computations that might lose precision or overflow, whose result is stored in a larger type, are suspicious since, by computing on the larger type from the beginning, one could avoid approximations and overflows.

Properties

Class Name Cast: Integer to Floating Point (Java)
Significance reliability
Mnemonic JAVA.CAST.FTRUNC
Categories
CWE CWE:192 Integer Coercion Error
CERT-Java CERT-Java:NUM12-J Ensure conversions of numeric types to narrower types do not result in lost or misinterpreted data
  CERT-Java:NUM13-J Avoid loss of precision when converting primitive integers to floating-point
Availability Available for Java and Kotlin.
Enabling Checks for this warning class are enabled by default. To disable them, add the following WARNING_FILTER rule to the project configuration file.
WARNING_FILTER += discard class="Cast: Integer to Floating Point (Java)"

Example

public class DocumentationExamples {

    public static void main(String[] args) {
        double d = (double) (exp1() / exp2()); // "Cast: Integer to Floating Point (Java)" warning issued here

        System.out.println("d = " + d);
    }

    private static int exp1() {
        return 2+1;
    }
    
    private static int exp2() {
        return 3+4;
    }
}

In this example, the programmer probably intended to set d to the real value of fraction 3/7, or as close to this value as can be represented by a double. However, due to operator precedence, d is set to 0 because the integer division is performed before casting.

Instead, use one of the following.

Resolution

If the result of a computation requires a particular type, compute from the beginning on that type instead of applying a type conversion at the end of the computation. Make sure you place the brackets correctly when performing math operations involving a cast.

Relevant Configuration File Parameters

The following configuration file parameters affect checks for this warning class.

 

To report problems with this documentation, please visit https://support.codesecure.com/.