...
Wiki Markup |
---|
Avoid using the primitive floating point types when precise computation is necessary,. Avoid them especially when performing currency calculations. RatherInstead, consider alternative representations that are able to completely represent the necessary values. Whatever representation you choose, 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 1991|AA. Bibliography#Goldberg 91]\] for an introduction to these issues. |
...
Code Block |
---|
|
double dollar = 1.000;
double dime = 0.110;
int number = 7;
System.out.println ("A dollar less " + number + " dimes is $" +
(dollar - number * dime) );
|
Because the value 1/10 lacks an exact representation in either Java floating point type — and, indeed, in any floating point format that uses a binary mantissa — this program prints
Code Block |
---|
A dollar less 7 dimes is $0.29999999999999993
|
Compliant Solution
This compliant solution uses an integer type (such as long
) and works in 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
|
Compliant Solution
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
|
Risk Assessment
Using a representation other than floating point can allow for more precision and accuracy for critical arithmetic.
...