【发布时间】: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 上对此进行了测试
【问题讨论】:
-
使用
decimal类型而不是double,后者是浮点数,因此具有固有的不精确性; stackoverflow.com/questions/6831217/double-vs-decimal-in-mysql -
我建议您使用 DECIMAL 类型,而不是 DOUBLE
-
sqlfiddle.com/#!2/cc2bf/1 。结果为 848。
-
尝试使用
round().. -
我更喜欢以 7 为基数的编号系统,只是为了摆脱黑客