问题
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.
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?
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);
Edit: 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?
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.
回答1:
This behavior is expected for the floating point number. You can read how the IEEE 754 works https://en.wikipedia.org/wiki/IEEE_754.
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)
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
回答2:
Use BigDecimal if you need precision doc.
来源:https://stackoverflow.com/questions/63841429/incorrect-double-values-returned-from-mysql-to-java