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?
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).
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With