Computers can represent only a finite number of digits. It is therefore impossible to precisely represent repeating binary -representation valuessequences of floating point numbers. This includes many finite decimal numbers, such as 1/10.
...
Noncompliant Code Example
This very simple example attempts to do noncompliant code example performs some basic currency calculations:.
Code Block | ||
---|---|---|
| ||
double dollar = 1.0; double dime = 0.1; int number = 7; System.out.println ("A dollar less " + number + " dimes is $" + (dollar - number*dime) ); |
...
A dollar less 7 dimes is $0.29999999999999993
Compliant Solution
A better approach is to use This compliant solution uses an integer type (such as long
) and work works in cents rather than dollars.
...
A dollar less 7 dimes is 30 cents
Compliant Solution
...
An alternative approach is to use the BigDecimal type, though it is less efficient performance wise.
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) )) ); |
...