DOUBLE vs DECIMAL 區別

對於財務計算,最好使用DECIMAL類型html

The example from MySQL documentation http://dev.mysql.com/doc/refman/5.1/en/problems-with-float.html (i shrink it, documentation for this section is the same for 5.5)
mysql


mysql> create table t1 (i int, d1 double, d2 double);sql


mysql> insert into t1 values (2, 0.00  , 0.00),this

                             (2, -13.20, 0.00),orm

                             (2, 59.60 , 46.40),htm

                             (2, 30.40 , 30.40);ci


mysql> select i, sum(d1) as a, sum(d2) as b from t1 group by i having a <> b;get

+------+-------------------+------+it

| i    | a                 | b    |io

+------+-------------------+------+

|    2 | 76.80000000000001 | 76.8 |

+------+-------------------+------+

1 row in set (0.00 sec)

Basically if you sum a you get 0-13.2+59.6+30.4 = 76.8. If we sum up b we get 0+0+46.4+30.4=76.8. The sum of a and b is the same but MySQL documentation says:


A floating-point value as written in an SQL statement may not be the same as the value represented internally.

If we repeat the same with decimal:


mysql> create table t2 (i int, d1 decimal(60,30), d2 decimal(60,30));

Query OK, 0 rows  affected (0.09 sec)


mysql> insert into t2 values (2, 0.00  , 0.00),

                             (2, -13.20, 0.00),

                             (2, 59.60 , 46.40),

                             (2, 30.40 , 30.40);

Query OK, 4 rows affected (0.07 sec)

Records: 4  Duplicates: 0  Warnings: 0


mysql> select i, sum(d1) as a, sum(d2) as b from t2 group by i having a <> b;

Empty set (0.00 sec)

The result as expected is empty set.


So as long you do not perform any SQL arithemetic operations you can use DOUBLE, but I would still prefer DECIMAL.


Another thing to note about DECIMAL is rounding if fractional part is too large. Example:


mysql> create table t3 (d decimal(5,2));

Query OK, 0 rows affected (0.07 sec)


mysql> insert into t3 (d) values(34.432);

Query OK, 1 row affected, 1 warning (0.10 sec)


mysql> show warnings;

+-------+------+----------------------------------------+

| Level | Code | Message                                |

+-------+------+----------------------------------------+

| Note  | 1265 | Data truncated for column 'd' at row 1 |

+-------+------+----------------------------------------+

1 row in set (0.00 sec)


mysql> select * from t3;

+-------+

| d     |

+-------+

| 34.43 |

+-------+

1 row in set (0.00 sec)

相關文章
相關標籤/搜索