gpt4 book ai didi

java - Hibernate 的浮点映射精度

转载 作者:塔克拉玛干 更新时间:2023-11-02 07:50:09 26 4
gpt4 key购买 nike

我试图在 MySQL 数据库中存储一个 float ,但 Hibernate 得到的值与列中存储的值不同,

在我的应用程序中,我计算:

float subtotal = 160.5f;
float ammount = (float) (subtotal * 0.1f); // this way I get the 10%
receipt.setAmmount(ammount);
receipt.save();

如果我记录这个金额,我会得到这样的结果:

19/04/2013 10:17:20 [INFO] ServiceImpl: Added ammount x $16.05

我在 mysql 数据库中的列 ammountFLOAT UNSIGNED 并且当我进行选择时我获得 16.05 作为值但是后来,当我使用 Hibernate 获取该对象时ammount 字段是 16.049999237060547。

我的 hbm 专栏如下所示:

<property name="ammount" type="float"></property>

我正在阅读 herehere建议在 Java 中使用 BigDecimal 而不是 FloatDouble 为了钱,但我无法得到我应该使用什么数据类型我的数据库或如何配置 Hibernate 以使用该数据类型,谢谢!

最佳答案

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

SEE HERE

关于java - Hibernate 的浮点映射精度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16105903/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com