Search code examples
javabigdecimal

Is BigDecimal necessary if no calculations are done with the monetary amount?


I have a Java program that reads data from a database, and shows it on a user interface. One of these data types is a money amount - and so it automatically triggers me to use BigDecimal as explained here . However in my case I don't do anything with this field except

  1. render it on the UI.
  2. give it another application (over http) who may write it into another database.

Considering the data in the database is of a type similar to double, I don't see any advantage into casting that double precision database field into a BigDecimal because it just gets converted to a string anyway (either for the UI, or for the webservice).

Am I missing something?


Solution

  • There is no requirement to use BigDecimal for monetary values however you must ensure that the amount is stored precisely without any rounding or precision problems normally encountered in float or double data types.

    There are few ways to achieve this:

    1. Java 9 comes with JSR 354: Money and Currency API classes e.g. MonetaryAmount.
    2. Store the amount as long using the smallest meaningful currency unit e.g. for USD it's the cent. Look out because some currencies don't use fractional units e.g. YEN.
    3. Mentioned BigDecimal.
    4. Store the amount as String if it doesn't require any processing on your side. It's an ugly approach but if you are only passing the amounts around it might do e.g. read from XML and expose using REST API.