...
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) ); |
Unfortunately, because of Because the value 1/10 cannot be represented precisely lacks an exact representation in either Java floating point type — and, indeed, in any binary floating point format , that uses a binary mantissa — this program prints
A dollar less 7 dimes is $0.29999999999999993
...
This code outputs: A dollar less 7 dimes is 30 cents
Compliant Solution
An alternative approach is to use the BigDecimal
type, but it is less efficient.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) )) ); |
...
Wiki Markup |
---|
\[[Bloch 2008|AA. Bibliography#Bloch 08]\] Item 48: Avoid {{float}} and {{double}} if exact answers are required \[[Bloch 2005|AA. Bibliography#Bloch 05]\] Puzzle 2: Time for a Change \[[Goldberg 1991|AA. Bibliography#Goldberg 91]\] \[[JLS 2005|AA. Bibliography#JLS 05]\] [Section 4.2.3, Floating-Point Types, Formats, and Values|http://java.sun.com/docs/books/jls/third_edition/html/typesValues.html#4.2.3], "Floating-Point Types, Formats, and Values" |
...
07. Floating Point (FLP) 07. Floating Point (FLP) FLP01-J. Take care in rearranging floating point expressions