Day 5: Q & A

Q: Our class notes mentioned that you should use BigDecimal in Java for financial data. Why can’t you just use double or float?

A: In Java, the result of any floating point number is not exact. Therefore, we should not be using them for financial calculations.

When I tried experimenting with the use of BigDecimal for one of our hw assignments, for a while, I didn’t realize that I was using the wrong constructor!

Instead of using the BigDecimal with a String constructor, I was using the constructor that accepts a double as an argument.

An example of using BigDecimal constructed with a double value:

BigDecimal amount1 = new BigDecimal(7030.15);

When I printed the contents of the amount1 object above, I noticed that there was something wrong with the rounding. When I googled to try to figure out how to round the number that was printed to the screen to the hundreds place, it was then when I realized that I was using the wrong constructor! The correct way to instantiate the object is shown below:

BigDecimal amount2 = new BigDecimal("7030.15");

To summarize, here is what I learned today:

  • The result of floating point numbers is not exact, which makes them unsuitable for any financial calculation which requires exact result and not approximation.
  • This means that you should not use float or double for monetary calculations.
  • When using BigDecimal, use the String constructor (NOT the constructor that accepts a double for the argument).
Like what you read? Give Katherine Guzman a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.