从 mysql 返回到 java 的双精度值不正确 [英] Incorrect double values returned from mysql to java

查看:71
本文介绍了从 mysql 返回到 java 的双精度值不正确的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我试图从 mysql 到 java 读取一些双精度值.我正在使用 mybatis 映射器读取我的值并将值作为映射返回.

So I was trying to read some double values from mysql to java. I am using a mybatis mapper to read my values and return the value as a map.

当我在 sql 中运行我的查询时,我的值是 -42295.8451869851 但是当我使用 mybatis 从查询中选择相同的内容并将其放入 java Hashmap 时,该值更改为 <代码>{Double@25327}-42295.84518699004.为什么会出现这种异常情况,我该如何预防?

When I run my query in sql, my value comes out to be -42295.8451869851 but when I use mybatis to pick the same from a query and put it in a java Hashmap the value changes to {Double@25327}-42295.84518699004 . Why is this anomaly and what can I do to prevent it?

这是我使用的mybatis查询行:我正在使用 org.apache.ibatis.session.SqlSession;

This is the mybatis query line I am using: I am using the class org.apache.ibatis.session.SqlSession;

List<Map<String, Object>> myListMaps =  getSqlSession().selectList(QUERY_NAME, queryParameters);

看了几个回复后,我意识到我需要使用 bigDecimal 而不是 Double/Float.所以我将重新定义我的问题来解决我在这里的目的.有没有什么办法告诉mybatis某个sql类型要映射到BigDecimal而不是HashMap中的Double/Float?

After looking at few responses, I realize that I need to somwhow use bigDecimal instead of Double/Float. So I will reframe my question to solve my purpose here. Is there any way to tell mybatis that a certain sql type is to be mapped to BigDecimal instead of Double/Float in a HashMap?

我还从 sql 中提取了其他值,例如 integervarchar,这些值正在转换为所需的 integer 和 <代码>字符串自动在java中,我希望它们按原样选择.只需要将双打改为 bigdecimal.

I also have other values being picked up from sql like integer and varchar that are being converted to the required types of integer and string in java automatically and I want them picked as it is. Just need to change the doubles to bigdecimal.

推荐答案

此行为是浮点数所期望的.您可以阅读 IEEE 754 的工作原理https://en.wikipedia.org/wiki/IEEE_754.

This behavior is expected for the floating point number. You can read how the IEEE 754 works https://en.wikipedia.org/wiki/IEEE_754.

但我认为还有另一个问题正在发生.你说这个数字是双精度(64 位),但根据结果,它看起来被转换为浮点(32 位)

But I think there is another issue happening. You say that the number is double (64-bit), but based on the result it look that it gets converted to float(32-bit)

-42295.8451869851 -> 0xC0E4A6FB0BC59380 (64bit) - 0xC72537D8 (32bit)

-42295.84518699004 -> 0xC0E4A6FB0BC59627 (64bit)- 0xC72537D8 (32bit)

如果要保持精度正确,则需要在 DB 中正确定义它,然后在 Java 中使用 https://docs.oracle.com/javase/8/docs/api/java/math/BigDecimal.html

If you want to keep the precision correct then you need to define it correctly both in DB and then in Java use https://docs.oracle.com/javase/8/docs/api/java/math/BigDecimal.html

这篇关于从 mysql 返回到 java 的双精度值不正确的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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