Java Reference
In-Depth Information
BigDecimal
Rounding error is a constant source of headaches for programmers who work with
floating-point numbers. In response, Java has a class
java.math.BigDecimal
that
provides arbitrary precision arithmetic, in a decimal representation. This works
around the problem of
0.1
not having a finite representation in binary, but there are
still some edge conditions when converting to or from Java's primitive types, as you
can see:
double
d
=
0.3
;
System
.
out
.
println
(
d
);
BigDecimal
bd
=
new
BigDecimal
(
d
);
System
.
out
.
println
(
bd
);
bd
=
new
BigDecimal
(
"0.3"
);
System
.
out
.
println
(
bd
);
However, even with all arithmetic performed in base-10, there are still numbers,
such as
1/3
, that do not have a terminating decimal representation. Let's see what
happens when we try to represent such numbers using
BigDecimal
:
bd
=
new
BigDecimal
(
BigInteger
.
ONE
);
bd
.
divide
(
new
BigDecimal
(
3.0
));
System
.
out
.
println
(
bd
);
// Should be 1/3
As
BigDecimal
can't represent
1/3
precisely, the call to
divide()
blows up with
ArithmeticException
. When working with
BigDecimal
, it is therefore necessary to
be acutely aware of exactly which operations could result in a nonterminating deci‐
mal result. To make matters worse,
ArithmeticException
is an unchecked, runtime
exception and so the Java compiler does not even warn about possible exceptions of
this type.
As as a final note on floating-point numbers, the paper “What Every Computer Sci‐
entist Should Know About Floating-Point Arithmetic” by David Goldberg should be
considered essential further reading for all professional programmers. It is easily
and freely obtainable on the Internet.
Java's Standard Library of Mathematical Functions
To conclude this look at Java's support for numeric data and math, let's take a quick
tour of the standard library of functions that Java ships with. These are mostly static
helper methods that are located on the class
java.lang.Math
and include functions
like:
abs()
Returns the absolute value of a number. Has overloaded forms for various
primitive types.