使用JPA和Oracle在数据库中存储尾随零 [英] Storing trailing zeroes in database with JPA and Oracle

查看:278
本文介绍了使用JPA和Oracle在数据库中存储尾随零的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在我的数据库中存储价格。我正在使用JPA,所以我有这样的模型:

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;
}

问题是当我用4.20这样的值填写价格表格输入时,在我的Oracle数据库中,我得到4.2,失去了尾随零。

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?

编辑:由于我正在使用JPA,因此我必须避免在本机Oracle方言中编写查询。要存储产品(及其价格),我只需编写类似 em.persist(product)的内容,其中em是EntityManager

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

推荐答案

你无法解决它,我认为这不是问题。这就是Oracle如何存储 NUMBER 值:所需的精度最低。如果您输入的价格为 4.00 ,则会将其存储为 4

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.

请注意,在显示值时,Java不会默认为两位小数。你需要指定小数位数。

Note that Java won't default to two decimals either when displaying the value. You need to specify the number of decimal places.

如果可能的话,我会使用 BigDecimal 而不是价格浮动 float 类型不准确。另一种方法是使用整数类型之一( int long )并自行管理小数位。

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.

要格式化Java代码中显示的价格,请使用 String.format(%。2f,price)

To format the price for display in your Java code, use String.format("%.2f", price).

要格式化Oracle查询中的价格,请使用 TO_CHAR

To format the price in an Oracle query, use TO_CHAR:

SELECT TO_CHAR(price, '999999990.00'), etc.

选择最适合您的占位符数量,并注意Oracle将在结果的开头添加一个额外的空格。如果数字是负数,则意味着保持减号,但对于零/正数,它是一个空格。要摆脱空间,请使用 TO_CHAR 中的 FM 修饰符:

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.

这篇关于使用JPA和Oracle在数据库中存储尾随零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆