为什么MySQL浮点与Java浮点不同?
我在MySQL float列中插入一个浮点值1223473,当我得到它时,该值变为1223470
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
public class Main {
public static void main(String[] args) throws Exception {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
PreparedStatement pstmt = null;
try {
// SETUP
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://...");
stmt = conn.createStatement();
stmt.execute("DROP TABLE IF EXISTS ttt");
stmt.execute("CREATE TABLE ttt (value FLOAT)");
// INPUT VALUE
float input = 1.223473E6f;
print(" Input", input);
pstmt = conn.prepareStatement("INSERT INTO ttt VALUES (?)");
pstmt.setFloat(1, input);
pstmt.execute();
// OUTPUT VALUES
rs = stmt.executeQuery("SELECT value, "
+ "AVG(value) as avg, MIN(value) as min, "
+ "MAX(value) as max, value + 0 as plus, "
+ "value * 1 as mult, "
+ "cast(value as decimal) as valcast "
+ "FROM ttt;");
rs.next();
System.out.println();
print("Output", rs.getFloat("value"));
print(" AVG", rs.getFloat("avg"));
print(" MIN", rs.getFloat("min"));
print(" MAX", rs.getFloat("max"));
print(" +0", rs.getFloat("plus"));
print(" *1", rs.getFloat("mult"));
print(" CAST", rs.getFloat("valcast"));
} finally {
if (stmt != null)
stmt.close();
if (pstmt != null)
pstmt.close();
if (conn != null)
conn.close();
}
}
private static void print(String name, float value) {
System.out.println(name + ": " + value + " (0x"
+ Integer.toHexString(Float.floatToRawIntBits(value)) + ")");
}
以下是输出:
Input: 1223473.0 (0x49955988)
Output: 1223470.0 (0x49955970)
AVG: 1223473.0 (0x49955988)
MIN: 1223473.0 (0x49955988)
MAX: 1223473.0 (0x49955988)
+0: 1223473.0 (0x49955988)
*1: 1223473.0 (0x49955988)
CAST: 1223473.0 (0x49955988)
使用MySQL客户端也可以看到相同的行为
我无法解释为什么输入值与输出值不同。此外,为什么应用操作会给出正确的值?即使有其他价值观,我也会有同样的行为。例如,如果使用1223472而不是122473,则输出值将为1223470。这看起来像是失去了精确性。但为什么对其应用操作会准确返回输入值呢?看起来MySQL存储的精度比它显示的要高
这看起来不像是对浮点类型的典型误解,人们试图在浮点中放入过多的数字:
System.out.println(1223473f == 1223470f); // gives false
System.out.println(123456789f == 123456791f); // gives true (too many digits)
最后,我不知道该怎么想
mysql> create table ttt (value float);
Query OK, 0 rows affected (0.04 sec)
mysql> INSERT INTO ttt VALUES (1223473);
Query OK, 1 row affected (0.00 sec)
mysql> select * from ttt;
+---------+
| value |
+---------+
| 1223470 |
+---------+
1 row in set (0.00 sec)
mysql> SELECT * FROM ttt WHERE value = 1223470;
Empty set (0.00 sec)
mysql> SELECT * FROM ttt WHERE value = 1223473;
+---------+
| value |
+---------+
| 1223470 |
+---------+
1 row in set (0.00 sec)
为什么值会改变
# 1 楼答案
您正在使用
float
作为数据类型。您没有足够的精度来表示1223473.0。根据MySQL documentation,浮点数也受“平台或实现依赖项”的约束将列上的数据类型更改为
double
(或decimal
),这将解决您的问题。见this SQLFiddle确认对} 值等聚合函数。文档中不清楚,但我强烈怀疑,如果使用
float
或double
的值执行SUM, AVG, return a ^{MIN
、MAX
、+ 0
或* 1
也会产生一种可以“保存结果值”的数据类型您应该知道浮点操作应该在tolerance(即阈值)内执行,这也是MySQL文档中指定的