How the BigDecimal class helps Java get its arithmetic right 1
How the BigDecimal class
helps Java get
its arithmetic right
When you use Java for simple business arithmetic, you may be surprised to
discover that Java doesn’t always produce the right answers. If, for example,
you use the double data type for an invoice’s subtotal, sales tax, and total, your
arithmetic expressions may deliver inaccurate results. I’ll illustrate this in a
moment.
The problem is that floating-point numbers can’t represent all decimal
numbers with complete accuracy. Then, when you round the results to two
decimal places, you can get errors. The best solution in a case like this is to
use Java’s BigDecimal class, and that’s what you’ll learn to do in this
document.
This article has been excerpted from Murach’s Java SE 6, a book
by Joel Murach and Andrea Steelman. One of the unique features of
that book is its “paired pages” presentation method in which each topic
is presented in two pages, with a text page on the left and the related
figure page on the right.
To get the most from this “paired pages” method as you read this
article, please place the left and right pages side-by-side, whether you
view them in the Adobe Reader or print them out. You’ll soon find that
this approach not only helps you learn faster but also works great for
reference.
Then, to learn more about this book, please go to our web site.
There, you can find out how this book differs from other Java books,
view the table of contents, download sample applications, and more.
MIKE MURACH & ASSOCIATES, INC.
1-800-221-5528 • (559) 440-9071 • Fax: (559) 440-0963
murachbooks@murach.com • www.murach.com
Copyright © 2007 Mike Murach & Associates. All rights reserved.
An Invoice application ................................................................................. 2
The code for the application ...................................................................................................... 2
The math problems in the Invoice application .......................................................................... 4
How to use the BigDecimal class ............................................................... 6
The constructors and methods of the BigDecimal class ........................................................... 6
How to use BigDecimal arithmetic in the Invoice application.................................................. 8
Summary ..................................................................................................... 10