Reputation: 6494
I'm trying to store a float in a MySQL database but Hibernate gets a differente value than what is stored in the column,
In my app I calculate:
float subtotal = 160.5f;
float ammount = (float) (subtotal * 0.1f); // this way I get the 10%
receipt.setAmmount(ammount);
receipt.save();
If I log that ammount I get something like this:
19/04/2013 10:17:20 [INFO] ServiceImpl: Added ammount x $16.05
My column ammount
in the mysql db is FLOAT UNSIGNED
and when I do a select I obtain 16.05 as the value but later, when I fetch that object with Hibernate the ammount field is 16.049999237060547.
My hbm column looks like this:
<property name="ammount" type="float"></property>
I was reading here and here that is recommended to use BigDecimal
in Java instead of Float
or Double
for money, but I can't get what data type should I use in my database or how to config Hibernate to use that datatype, thanks!
Upvotes: 3
Views: 10731
Reputation: 7335
I think I'd try defining your column as NUMBER(6,2) on the database and using a BigDecimal object in your java layer. You should not be using float for currencies.
Upvotes: 2
Reputation: 2273
The recommended Java mapping for the DECIMAL and NUMERIC types is java.math.BigDecimal. The java.math.BigDecimal type provides math operations to allow BigDecimal types to be added, subtracted, multiplied, and divided with other BigDecimal types, with integer types, and with floating point types.
The method recommended for retrieving DECIMAL and NUMERIC values is ResultSet.getBigDecimal. JDBC also allows access to these SQL types as simple Strings or arrays of char. Thus, Java programmers can use getString to receive a DECIMAL or NUMERIC result. However, this makes the common case where DECIMAL or NUMERIC are used for currency values
Upvotes: 3