...
Wiki Markup |
---|
Avoid using the primitive floating point types when precise computation is necessary. Avoid them especially when performing currency calculations. Instead, consider alternative representations that are able to completely represent the necessary values. Whatever representation you choose, you must carefully and methodically estimate the maximum cumulative error of the computations to ensure that the resulting error is within acceptable tolerances. Consider using numerical analysis to properly understand the problem. See \[[Goldberg 1991|AA. Bibliography#Goldberg 91]\] for an introduction to these issues. |
Noncompliant Code Example
This noncompliant code example performs some basic currency calculations.
...
Code Block |
---|
A dollar less 7 dimes is $0.29999999999999993 |
Compliant Solution
This compliant solution uses an integer type (such as long
) and works with cents rather than dollars.
...
Code Block |
---|
A dollar less 7 dimes is 30 cents |
Compliant Solution
This compliant solution uses the BigDecimal
type which provides exact representation of decimal values. Note that on most platforms computations performed using BigDecimal
are less efficient than those performed using primitive types. The importance of this reduced efficiency is application-specific.
...
Code Block |
---|
A dollar less 7 dimes is $0.3 |
Risk Assessment
Using a representation other than floating point can allow for more precision and accuracy for critical arithmetic.
Guideline | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
FLP00-J | low | probable | high | P2 | L3 |
Automated Detection
Automated detection of floating point arithmetic is straight-forward; determining which code suffers from insufficient precision is not feasible in the general case. Heuristic checks, such as flagging floating point literals that cannot be represented precisely, may be useful.
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this guideline on the CERT website.
Related Guidelines
C Secure Coding Standard: FLP02-C. Avoid using floating point numbers when precise computation is needed
C++ Secure Coding Standard: FLP02-CPP. Avoid using floating point numbers when precise computation is needed
Bibliography
Wiki Markup |
---|
\[[Bloch 2008|AA. Bibliography#Bloch 08]\] Item 48: Avoid {{float}} and {{double}} if exact answers are required \[[Bloch 2005|AA. Bibliography#Bloch 05]\] Puzzle 2: Time for a Change \[[Goldberg 1991|AA. Bibliography#Goldberg 91]\] \[[JLS 2005|AA. Bibliography#JLS 05]\] [Section 4.2.3|http://java.sun.com/docs/books/jls/third_edition/html/typesValues.html#4.2.3], "Floating-Point Types, Formats, and Values" |
...