Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

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:

...

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.

...

A dollar less 7 dimes is 30 cents

Compliant Solution 2

An alternative approach is to use the BigDecimal type.

...

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. Avoid using floating point numbers when precise computation is needed.

This rule appears in the C++ Secure Coding Standard as FLP02-CPP. Avoid using floating point numbers when precise computation is needed.

References

Wiki Markup
\[[JLS 05|AA. Java References#JLS 05]\] [Section 4.2.3, Floating-Point Types, Formats, and Values|http://java.sun.com/docs/books/jls/third_edition/html/typesValues.html#4.2.3]
\[[Bloch 08|AA. Java References#Bloch 08]\] Item 48: Avoid {{float}} and {{double}} if exact answers are required
\[[Bloch 05|AA. Java References#Bloch 05]\] Puzzle 2: Time for a Change
\[[Goldberg 91|AA. Java References#Goldberg 91]\]

...