Computers can represent only a finite number of digits. It is therefore impossible to precisely represent repeating binary-representation values. This includes many finite decimal numbers, such as 1/10.
When precise computation is necessary, and especially when doing currency calculations, consider alternative representations that may be able to completely represent values rather than the floating point representations float
and double
.
Noncompliant Code Example
This very simple example attempts to do some basic currency calculations:
double dollar = 1.0; double dime = 0.1; int number = 7; System.out.println ("A dollar less " + number + " dimes is $" + (dollar - number*dime) );
Unfortunately, because of the imprecision of floating point arithmetic, this program prints:
A dollar less 7 dimes is $0.29999999999999993
Compliant Solution
A better approach is to use an integer type (such as long
) and work in cents rather than dollars.
long dollar = 100; long dime = 10; int number = 7; System.out.println ("A dollar less " + number + " dimes is " + (dollar - number*dime) + " cents" );
This code prints out:
A dollar less 7 dimes is 30 cents
Compliant Solution 2
An alternative approach is to use the BigDecimal type.
import java.math.BigDecimal; // ... BigDecimal dollar = new BigDecimal("1.0"); BigDecimal dime = new BigDecimal("0.1"); int number = 7; System.out.println ("A dollar less " + number + " dimes is $" + (dollar.subtract( new BigDecimal(number).multiply(dime) )) );
This code prints out:
A dollar less 7 dimes is $0.3
Risk Assessment
Using a representation other than floating point may allow for more precision and accuracy for critical arithmetic.
Recommendation |
Severity |
Likelihood |
Remediation Cost |
Priority |
Level |
---|---|---|---|---|---|
FLP00-J |
low |
probable |
high |
P2 |
L3 |
Automated Detection
TODO
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
Other Languages
This rule appears in the C Secure Coding Standard as FLP02-C. Consider avoiding floating point numbers when precise computation is needed.
References
[JLS 05] Section 4.2.3, Floating-Point Types, Formats, and Values
[Bloch 08] Item 48: Avoid float
and double
if exact answers are required
[Bloch 05] Puzzle 2: Time for a Change
05. Floating Point (FLP) 05. Floating Point (FLP) FLP01-J. Take care in rearranging floating point expressions