【问题标题】:Mysql SUM function returns returns wrong decimal valuesMysql SUM 函数返回返回错误的十进制值
【发布时间】:2013-05-15 11:02:48
【问题描述】:

我有下表和测试数据集:

CREATE TABLE `test` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `desc` varchar(20) DEFAULT NULL,
  `amount` double DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8

    insert into `test` (`id`, `desc`, `amount`) values('5',NULL,'847.3');
    insert into `test` (`id`, `desc`, `amount`) values('6',NULL,'-847');
    insert into `test` (`id`, `desc`, `amount`) values('7',NULL,'847.3');
    insert into `test` (`id`, `desc`, `amount`) values('8',NULL,'-847');
    insert into `test` (`id`, `desc`, `amount`) values('9',NULL,'847.4');

所以表格看起来像:

现在我的问题是当我使用时:

SELECT SUM(amount) FROM test; 

我得到以下结果847.9999999999999,而不是预期的848

任何想法为什么我没有得到四舍五入的小数?

更新:

我已经在 MySQL Server: 5.5.17 (windows) 和 MySQL Server: 5.5.20 Centos 上对此进行了测试

【问题讨论】:

标签: mysql sum


【解决方案1】:

这是floating-point numbers 由计算机表示的方式所固有的问题。基本上,一些以 10 为底的值,可以用有限的数字写入,不能以 2 为底。

大多数情况下,此类近似值不会引起注意,因为您只显示少量十进制数字。但是,当您开始将这些近似值相加和相乘时,误差会累积到明显的程度。

这就是DECIMAL 类型存在的原因。它本质上将十进制值表示为一个整数,除以或乘以 10 的幂。使用这种表示形式,永远不会进行近似。

【讨论】:

    猜你喜欢
    • 2018-06-12
    • 2022-01-19
    • 2021-06-04
    • 1970-01-01
    • 2015-12-28
    • 2017-07-30
    • 1970-01-01
    • 1970-01-01
    • 2014-08-10
    相关资源
    最近更新 更多