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

Compare with Current View Page History

« Previous Version 13 Next »

Computers can represent only a finite number of digits. It is therefore impossible to precisely represent repeating binary sequences of floating point numbers. This includes many finite decimal numbers, such as 1/10 which have repeating binary representations.

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 noncompliant code example performs 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

This compliant solution uses an integer type (such as long) and works 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

An alternative approach is to use the BigDecimal type, though it is less efficient.

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. 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

[[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
[[Goldberg 91]]


06. Floating Point (FLP)      06. Floating Point (FLP)      FLP01-J. Take care in rearranging floating point expressions

  • No labels