You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 2 Next »

Converting a value of type float to the type double is a widening primitive conversion. Refer to the guideline INT33-J. Do not cast numeric types to wider floating-point types without range checking for more details about such conversions. If the value of the float variable must be represented exactly using the double type, an explicit assignment is inappropriate. Note that this is a problem that results from the limited capacity of computers in representing floating point values precisely.

Noncompliant Code Example

In this noncompliant code example, the programmer attempts to convert the fractional value 1/3 (represented by a variable of type float) to the double type. The correct representation of this fraction in floating point arithmetic is 0.33333334 (the last digit 4, is rounded up). When converted to double, instead of observing a value such as 0.3333333400000000 or 0.333333333333333, the programmer obtains an unexpected value because floating point arithmetic in Java rounds to the nearest, a mode defined by the IEEE 754 floating point standard. If the exact value lies midway between two valid floating point values, the lower one (with the least significant bit as 0) is chosen. If it is more than midway, a small positive error is introduced, else a small negative error. [[Mak 02]]

double d;
float f = 1/3f; // Contains the value 0.33333334
d = f; // Now contains the value 0.3333333432674408

Compliant Solution

If the exact value must be preserved, the string representation of the floating point number must be obtained. This can be converted to the double type without losing the initial precision.

double d;
float f = 1/3f; // Contains the value 0.33333334
d = Double.valueOf(String.valueOf(f)); // Now contains the value 0.33333334

Risk Assessment

Converting from float to double type when exact values are required can affect the precision of the converted value.

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

FLP05- J

low

likely

medium

P6

L2

Automated Detection

TODO

Related Vulnerabilities

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

References

[[API 06]]
[[JLS 05]]
[[Mak 02]] Section 3.7 "Another Look at Roundoff Errors"


FLP04-J. Check floating point inputs for exceptional values      07. Floating Point (FLP)      FLP30-J. Do not use floating point variables as loop counters

  • No labels