1. 程式人生 > 實用技巧 >不靠譜的FLOAT資料型別

不靠譜的FLOAT資料型別

今天在設計資料表時,突然發現原來FLOAT原來是很不靠譜的,所以在這裡建議大家換成DOUBLE型別,

原因是:

在mysql手冊中講到,在MySQL中的所有計算都是使用雙精度完成的,使用float(單精度)會有誤差,出現意想不到的結果。

在我們查詢資料時,MySQL使用64位十進位制數值的精度執行DECIMAL操作,float(5.54)=5.54如果出現精度丟失,這個是不等的。這樣,本來我們應該能查到的資料就會莫名其妙的消失。

轉自:

https://blog.csdn.net/sunhuaqiang1/article/details/47090367?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-3.channel_param&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-3.channel_param

一、引用剛師兄的一個例子,這是他在他機器上執行的結果

二、我在我電腦上測試如下:

mysql> desc t12;
+-------+---------------+------+-----+---------+-------+
| Field | Type          | Null | Key | Default | Extra |
+-------+---------------+------+-----+---------+-------+
| c1    | float(10,2)   | YES  |     | NULL    |       |
| c3    | decimal(10,2) | YES  |     | NULL    |       |
+-------+---------------+------+-----+---------+-------+
2 rows in set (0.00 sec)

mysql> desc t13;
+-------+---------------+------+-----+---------+-------+
| Field | Type          | Null | Key | Default | Extra |
+-------+---------------+------+-----+---------+-------+
| c1    | double(10,2)  | YES  |     | NULL    |       |
| c3    | decimal(10,2) | YES  |     | NULL    |       |
+-------+---------------+------+-----+---------+-------+
2 rows in set (0.00 sec)

mysql> truncate table t12;
Query OK, 0 rows affected (0.06 sec)

mysql> truncate table t13;
Query OK, 0 rows affected (0.05 sec)

mysql> insert into t12 values(1234567.23,1234567.23);
Query OK, 1 row affected (0.01 sec)

mysql> insert into t13 values(1234567.23,1234567.23);
Query OK, 1 row affected (0.01 sec)

mysql> select * from t12;
+------------+------------+
| c1         | c3         |
+------------+------------+
| 1234567.25 | 1234567.23 |
+------------+------------+
1 row in set (0.00 sec)

mysql> select * from t13;
+------------+------------+
| c1         | c3         |
+------------+------------+
| 1234567.23 | 1234567.23 |
+------------+------------+
1 row in set (0.00 sec)

三、查詢<深入淺出MySQL>原因為: