This rule may be deprecated and replaced by a similar guideline.
06/28/2014 -- Version 1.0
The Java language provides two primitive floating-point types,
double, which are associated with the single-precision 32-bit and double-precision 64-bit format values and operations specified by IEEE 754 [IEEE 754]. Each of the floating-point types has a fixed, limited number of mantissa bits. Consequently, it is impossible to precisely represent any irrational number (for example, pi). Further, because these types use a binary mantissa, they cannot precisely represent many finite decimal numbers, such as 0.1, because these numbers have repeating binary representations.
When precise computation is necessary, such as when performing currency calculations, floating-point types must not be used. Instead, use an alternative representation that can completely represent the necessary values.
When precise computation is unnecessary, floating-point representations may be used. In these cases, 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's work for an introduction to this topic [Goldberg 1991].
Noncompliant Code Example
This noncompliant code example performs some basic currency calculations:
Because the value 0.10 lacks an exact representation in Java floating-point type (or any floating-point format that uses a binary mantissa), on most platforms, this program prints the following:
This compliant solution uses an integer type (such as
int) and works with cents rather than dollars:
This code correctly outputs the following:
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.
This code outputs the following:
Using floating-point representations when precise computation is required can result in a loss of precision and incorrect values.
Automated detection of floating-point arithmetic is straightforward. However, 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, could be useful.
Floating-Point Arithmetic [PLF]
Android Implementation Details
The use of floating-point on Android is not recommended for performance reasons.
Item 48, "Avoid
Puzzle 2, "Time for a Change"