Pages

April 6, 2011

Java Doesn’t Make Money Easy

I am currently working on writing a small loan payment calculator application for Android, and trying to be a good boy and use the java.math.BigDecimal class to handle the money representations. It took me a bit to get it going, but I am really wishing I had gone “old school” and just used an integer and done all the calculations at the penny level.

The BigDecimal class methods initially seemed to be pretty straightforward. You just call the add, subtract, multiply, or divide methods like you would if you were doing normal calculations. So I wrote my test case, implemented the formula in my LoanCalculator class, and kicked off my test full of excitement about being able to tie all of this in to the Activity UI I had all set up. Nothing but red and a big stacktrace.

Exception in thread "main" java.lang.ArithmeticException: Non-terminating decimal expansion; no exact representable decimal result.

It turns out that when calling the BigDecimal.divide() method you need to specifically set the scale and rounding method so the object knows how to represent the decimal value in the cases where it is a repeating number, ex. 2/3 = 0.6666666666666…. I got that situated, got my test passed and moved on my way. I always wondered why I never saw BigDecimal used frequently and now I know why. Unless you pay attention to what you are doing and really read the API specification you will get errors and stacktraces that some devs would rather just avoid.

2 comments:

  1. How to earn money from online? Few years ago I was asking the question everybody. Nobody clearly answer me. But I found a website www.makemoney.solvewin.com and now I know how to earn real money using AdSense, Freelancer Job, Data Entry Job, Affiliated Program and more easy way to earn money $50 to unlimited amount per day!

    Thanks to www.makemoney.solvewin.com

    ReplyDelete
  2. Nice found. But I've found that it requires extra thoughts on implementing financial numbers. Different companies have different requirements on decimals. Such as payment system, some companies do ceiling and some others do floor, some even say floor on certain rules only. So using pure science math lib may not be what you exactly want. And you are right, going back to implementing integer as decimal is easier in some circumstances.

    ReplyDelete