DOUBLE vs DECIMAL 区别

对于财务计算,最好使用DECIMAL类型

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> create table t1 (i int, d1 double, d2 double);


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

                             (2, -13.20, 0.00),

                             (2, 59.60 , 46.40),

                             (2, 30.40 , 30.40);


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

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

| i    | a                 | b    |

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

|    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)


转载于:https://my.oschina.net/forrest420/blog/670283

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值