float,double容易產生誤差,對精確度要求比較高時,建議使用decimal來存,decimal在mysql記憶體是以字串儲存的,用於定義貨幣要求精確度高的資料。
[例子]
建立一個tab表(定義兩個欄位分別為float與decimal)
| 代碼如下 |
複製代碼 |
|
create table tab(col_f float(10,2), col_d decimal(10,2));
插入兩行記錄,做為實驗
insert into tab values(1234567.21, 1234567.21),(9876543.21, 9876543.12); |
在資料移轉中,float(M,D)是非標準定義,最好不要這樣使用。M為精度,D為標度。
| 代碼如下 |
複製代碼 |
|
mysql> create table t1(c1 float(10,2), c3 decimal(10,2));
Query OK, 0 rows affected (0.02 sec)
mysql> insert into t1 values(1234567.23, 1234567.23);
Query OK, 1 row affected (0.01 sec)
mysql> select * from t1;
+------------+------------+
| c1 | c3 |
+------------+------------+
| 1234567.25 | 1234567.23 |
+------------+------------+
1 row in set (0.02 sec)
mysql> insert into t1 values(9876543.21, 9876543.12);
Query OK, 1 row affected (0.00 sec)
mysql>
mysql> select * from t1;
+------------+------------+
| c1 | c3 |
+------------+------------+
| 1234567.25 | 1234567.23 |
| 9876543.00 | 9876543.12 |
+------------+------------+
2 rows in set (0.00 sec) |
不定義fload, double的精度和標度時,儲存按給出的數值儲存,這於OS和當前的硬體有關。
decimal預設為decimal(10,0)
因為誤差問題,在程式中,少用浮點數做=比較,可以做range比較。如果數值比較,最好使用decimal類型。
精度中,符號不算在內:
| 代碼如下 |
複製代碼 |
|
mysql> insert into t1 values(-98765430.21, -98765430.12);
Query OK, 1 row affected (0.01 sec)
mysql> select * from t1;
+--------------+--------------+
| c1 | c3 |
+--------------+--------------+
| 1234567.25 | 1234567.23 |
| 9876543.00 | 9876543.12 |
| -98765432.00 | -98765430.12 |
+--------------+--------------+
3 rows in set (0.00 sec) |
float佔4個位元組,double佔8個位元組,decimail(M,D)占M+2個位元組。
decimal 類型可以精確地表示非常大或非常精確的小數。大至 1028(正或負)以及有效位元多達 28 位的數字可以作為 decimal類型儲存而不失其精確性。該類型對於必須避免舍入錯誤的應用程式(如記賬)很有用。
float是浮點數,不能指定小數位。
decimal是精確數,可以指定精度。
對mysql 5來說 decimal(p,s)中p最大為65,S最大為30
decimal資料類型最多可儲存 38 個數字,它儲存了一個準確(精確)的數字表達法,不儲存值的近似值。
當資料值一定要按照指定精確儲存時,可以用帶有小數的decimal資料類型來儲存數字。
float和real資料類型被稱為近似的資料類型。不儲存精確值.當要求精確的數字狀態時,比如在財務應用程式中,在那些需要舍入的操作中,或在等值核對的操作中,就不使用這些資料類型。這時就要用integer、decimal、money或smallmone資料類型。
在 WHERE 子句搜尋條件中(特別是 = 和 <> 運算子),應避免使用float或real列。最好限制使用float和real列做> 或 < 的比較。
float 使用的資料類型就是C語言裡面的float, decimal使用的是mysql定義的decimal_t, 這個源檔案decimal.c我看過, 結構體時這麼定義的:
| 代碼如下 |
複製代碼 |
|
/**
intg is the number of *decimal* digits (NOT number of decimal_digit_t's !)
before the point
frac is the number of decimal digits after the point
len is the length of buf (length of allocated space) in decimal_digit_t's,
not in bytes
sign false means positive, true means negative
buf is an array of decimal_digit_t's
*/
typedef struct st_decimal_t {
int intg, frac, len;
my_bool sign;
decimal_digit_t buf[9];
} decimal_t; |
所以表示的數的精度和範圍就知道了