...
This noncompliant code example performs some basic currency calculations.
Code Block | ||
---|---|---|
| ||
double dollar = 1.00;
double dime = 0.10;
int number = 7;
System.out.println("A dollar less " + number + " dimes is $" +
(dollar - number * dime) );
|
Because the value 0.10 lacks an exact representation in either Java floating-point type (or any floating-point format that uses a binary mantissa), on most platforms, this program prints:
Code Block |
---|
A dollar less 7 dimes is $0.29999999999999993
|
...
This compliant solution uses an integer type (such as long
) and works with cents rather than dollars.
Code Block | ||
---|---|---|
| ||
long dollar = 100;
long dime = 10;
int number = 7;
System.out.println ("A dollar less " + number + " dimes is " +
(dollar - number * dime) + " cents" );
|
This code correctly outputs:
Code Block |
---|
A dollar less 7 dimes is 30 cents
|
...
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 | ||
---|---|---|
| ||
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 outputs:
Code Block |
---|
A dollar less 7 dimes is $0.3
|
...
Rule | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
NUM04-J | low | probable | high | P2 | L3 |
Automated Detection
Automated detection of floating-point arithmetic is straight forward. 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.
...
FLP02-C. Avoid using floating-point numbers when precise computation is needed | |
FLP02-CPP. Avoid using floating point numbers when precise computation is needed | |
Floating-Point Arithmetic [PLF] |
Android Implementation Details
The use of floating-point is not recommended for performance reasons on Android.
Bibliography
Item 48. Avoid | |
Puzzle 2. Time for a change | |
| |
[IEEE 754] |
|
[JLS 2005] |
03. Numeric Types and Operations (NUM) NUM05-J. Do not use denormalized numbers