我有下表和测试数据集:
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 上测试过了
最佳答案
这是方式固有的问题floating-point numbers由计算机代表。基本上,一些可以用有限位数书写的以 10 为基数的值不能用以 2 为基数表示。
大多数时候,这种近似值不会引起注意,因为您只显示少量小数位。但是,当您开始将这些近似值相加和相乘时,误差会累积到一个变得明显的点。
这就是为什么 DECIMAL
类型存在。它本质上将十进制值表示为整数,除以或乘以 10 的幂。使用这种表示法,不会进行任何近似。
关于Mysql SUM函数返回返回错误的十进制值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16563336/