Java Reference
In-Depth Information
System.out.printf("%.2f%n", 2.00 - 1.10);
This prints the right answer but does not represent a general solution to the underlying problem: It
still uses
double
arithmetic, which is binary floating-point. Floating-point arithmetic provides good
approximations over a wide range of values but does not generally yield exact results.
Binary
floating-point is particularly ill-suited to monetary calculations
, as it is impossible to represent
0.1— or any other negative power of 10— exactly as a finite-length binary fraction [EJ Item 31].
One way to solve the problem is to use an integral type, such as
int
or
long
, and to perform the
computation in cents. If you go this route, make sure the integral type is large enough to represent
all the values you will use in your program. For this puzzle,
int
is ample. Here is how the
println
looks if we rewrite it using
int
values to represent monetary values in cents. This version prints
90
cents
, which is the right answer:
System.out.println((200 - 110) + " cents");
Another way to solve the problem is to use
BigDecimal
, which performs exact decimal arithmetic.
It also interoperates with the SQL
DECIMAL
type via JDBC. There is one caveat:
Always use the
BigDecimal(String)
constructor, never
BigDecimal(double)
. The latter constructor creates an
instance with the
exact
value of its argument:
new BigDecimal(.1)
returns a
BigDecimal
representing 0.1000000000000000055511151231257827021181583404541015625. Using
BigDecimal
correctly, the program prints the expected result of
0.90
:
import java.math.BigDecimal;
public class Change {
public static void main(String args[]) {
System.out.println(new BigDecimal("2.00").
subtract(new BigDecimal("1.10")));
}
}
This version is not terribly pretty, as Java provides no linguistic support for
BigDecimal
.
Calculations with
BigDecimal
are also likely to be slower than those with any primitive type, which
might be an issue for some programs that make heavy use of decimal calculations. It is of no
consequence for most programs.
In summary,
avoid
float
and
double
where exact answers are required; for monetary
Search WWH ::
Custom Search