Rule Definition
The program could wind up using the wrong number and generate incorrect results. If the number is used to allocate resources or make a security decision, then this could introduce a vulnerability.
- A widening conversion of an int or a long value to float, or of a long value to double, may result in loss of precision - that is, the result may lose some of the least significant bits of the value. In this case, the resulting floating-point value will be a correctly rounded version of the integer value, using IEEE 754 round-to-nearest mode
Remediation
You can use Widening Primitive Conversion to avoid loss of precision.
Violation Code Sample
int i = (int) 33457.8f;
short i1 = (short)ic.readdata(); // VIOLATION if readdata returns long
int i1 = 1 + 2+ (int)3.5 // VIOLATION
Fixed Code Sample
A widening primitive conversion does not lose information about the overall magnitude of a numeric value.
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
-Despite the fact that loss of precision may occur, a widening primitive conversion never results in a run-time exception
Reference
https://cwe.mitre.org/data/definitions/681.html
http://www.informit.com/articles/article.aspx?p=174371
Related Technologies
Technical Criterion
ASCSM-CWE-681 - Numeric Types Incorrect Conversion
About CAST Appmarq
CAST Appmarq is by far the biggest repository of data about real IT systems. It's built on thousands of analyzed applications, made of 35 different technologies, by over 300 business organizations across major verticals. It provides IT Leaders with factual key analytics to let them know if their applications are on track.