A question of interest. I keep reading code of sample applications (some from respectable sources) that use type double to represent monetary values. On the other hand, not once did I come across comments stating evils of double. Could maybe someone outline benefits of BigDecimal?
The books vary on that question. Deitel and Deitel have a little inset saying to use BigDecimal or integer arithmetic. Barry Burd's book (at least the one I have read) seems happy to use floating-point. Even though he presents an example where there is a millionth-of-a-cent error. Joshua Bloch (Effective Java) and, even more so, Bloch and Gafter (Java Puzzlers) have examples in where floating-point arithmetic wll let you down badly. But Sunil Kumar is spot on.
Joined: Nov 11, 2008
Thanks for clarifications Is that that behavior of BigDecimal with a double constructor a known bug or expected behavior though?
As Campbell mentioned, Effective Java by Joshua Bloch has a very nice, succinct, and compelling explanation of why BigDecimal should be used rather than doubles, especially for monetary calculations. The item is named Avoid float and double if exact answers are required and is Item #31 in the first edition (ISBN-10: 0-201-31005-8) and Item #48 in the second edition (ISBN-10: 0-321-35668-3). It has some simple monetary calculation examples that show how easily and quickly doubles can corrupt results. It'd be well worth it to find a copy of this book in a library to read this information. Although in my humble opinion, all Java Developers should have a copy of this book and should read it annually.
If you want to investigate this subject in detail, the book Java� Number Cruncher: The Java Programmer's Guide to Numerical Computing by Ronald Mak (ISBN-10: 0-321-35668-3) covers the subject nicely. Given the complexity of the subject matter, it is an easy read. Although the last few chapters do get mathematically intense.