Java Reference
In-Depth Information
Listing 7.1. An Account POGO in Groovy that uses BigDecimal
Financial calculations are one of the reasons we need java.math.BigDecimal and
java.math.BigInteger . Using BigDecimal keeps round-off errors from being
sent into an account where it can accumulate over time. [ 1 ] It's easy to show how quickly
round-off errors can become a problem. Consider the following two lines:
1 If you haven't seen Office Space yet ( http://mng.bz/c6o8 ), you have a real treat ahead of you.
println 2.0d - 1.1d
println 2.0 - 1.1
The first line uses doubles, while the second line uses java.math.BigDecimal . The
first evaluates to 0.8999999999999999, while the second evaluates to 0.9. In the double
case I've only done a single calculation and already I have enough error to show up.
When coding in Java working with BigDecimal is awkward because it's a class rather
than a primitive. That means you can't use your normal +, *, - operators and have to use
the class's API instead.
 
Search WWH ::




Custom Search