How to use money data type in Java, SQL, ORM

What are best practises in using money data type in Java application?

Use BigDecimal. Using any primitive will lead to precision problems sooner or later.

And what about ORM and SQL in most popular databases.

Hibernate (and probably all others) can handle BigDecimal just fine. And it translates to the appropriate database type, which is usually DECIMAL.


You should use BigDecimal to represent monetary values.

From Bloch, J., Effective Java, 2nd ed, Item 48:

The float and double types are particularly ill-suited for monetary calculations because it is impossible to represent 0.1 (or any other negative power of ten) as a float or double exactly.

For example, suppose you have $1.03 and you spend 42c. How much money do you have left?

System.out.println(1.03 - .42);

prints out 0.6100000000000001.

The right way to solve this problem is to use BigDecimal, int or long for monetary calculations.

For SQL, I use NUMERIC(19,2).


In development circles, it is commonly considered best practice to use BigDecimal for money in Java. That is not to say it is always better than using double IMHO, but I would suggest you start with BigDecimal.

For SQL I suggest using a matching type NUMERIC or DECIMAL for BigDecimal and REAL for double.

Its is worth noting that all the investment banks and trading houses I have worked for use double with rounding for money (in C++ and Java). Conversely I have never seen BigDecimal used, but I have seen NUMERIC used in databases. For accounting purposes use BigDecimal.