Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

What are best practises in using money data type in Java application? Money should be in double variable? What about rounding, currencies and so on. Are special libraries for this? And what about ORM and SQL in most popular databases. As I know not in all SQL engines is Money data type. In that case NUMERIC(15,2), DECIMAL(15,2) or REAL data type should be use?

like image 1000
bltc Avatar asked Jan 28 '11 09:01

bltc


People also ask

What datatype should I use for money in SQL?

Unlike the DECIMAL data type, the MONEY data type is always treated as a fixed-point decimal number. The database server defines the data type MONEY(p) as DECIMAL(p,2). If the precision and scale are not specified, the database server defines a MONEY column as DECIMAL(16,2).

How do you represent money in Java?

Representing money: use BigDecimal , int , or long ( BigDecimal is the recommended default) the int and long forms represent pennies (or the equivalent, of course) BigDecimal is a little more inconvenient to use, but has built-in rounding modes.

What datatype is money?

Money Data Type. The money data type is an abstract data type. Money values are stored significant to two decimal places. These values are rounded to their amounts in dollars and cents or other currency units on input and output, and arithmetic operations on the money data type retain two-decimal-place precision.

Which data type should be used to store money?

The DECIMAL and NUMERIC types store exact numeric data values. These types are used when it is important to preserve exact precision, for example with monetary data. In MySQL, NUMERIC is implemented as DECIMAL, so the following remarks about DECIMAL apply equally to NUMERIC.


1 Answers

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.

like image 105
jpkrohling Avatar answered Sep 29 '22 20:09

jpkrohling