问题
I need to store prices in my database. I'm using JPA, so I've got a model like this:
@Entity
@Table(name="products")
public class Product {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private long id;
@Column(name="price")
private float price;
}
The problem is that when I fill price form inputs with values like "4.20", on my Oracle database I get "4.2", losing the trailing zero.
How can I solve this problem?
EDIT: Since I'm using JPA, I have to avoid writing queries in native Oracle dialect. To store products (with their prices) I simply write something like em.persist(product)
, where em is the EntityManager
回答1:
You can't solve it, and I'd suggest it's not a problem. That's just how Oracle stores NUMBER
values: with the least precision needed. If you entered the price as 4.00
it would be stored as 4
.
Note that Java won't default to two decimals either when displaying the value. You need to specify the number of decimal places.
And, if possible, I'd use BigDecimal
instead of float
for the price. The float
type isn't precise. An alternative is to use one of the integer types (int
or long
) and manage the decimal places yourself.
To format the price for display in your Java code, use String.format("%.2f", price)
.
To format the price in an Oracle query, use TO_CHAR:
SELECT TO_CHAR(price, '999999990.00'), etc.
Choose the number of placeholders that's best for you, and note that Oracle will put an extra space at the beginning of the result. It's meant to hold a minus sign if the number is negative, but for zero/positive it's a space. To get rid of the space use the FM
modifier in the TO_CHAR
:
SELECT TO_CHAR(price, 'FM999999990.00'), etc.
来源:https://stackoverflow.com/questions/18164865/storing-trailing-zeroes-in-database-with-jpa-and-oracle