MySQL 对 FLOAT 数据使用 SUM
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3907021/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using SUM on FLOAT data
提问by Emanuil Rusev
One table:
items(id, price)
一张表:
items(id, price)
Has one row:
id: 1, price: 565.8
有一行:
id:1,价格:565.8
SELECT price FROM items
gives 565.8
SELECT SUM(price) FROM items
gives 565.799987792969
instead of 565.8
which I'd expect.
SELECT price FROM items
给565.8
SELECT SUM(price) FROM items
给565.799987792969
,而不是565.8
我所期待。
Where does the 565.799987792969
come from?
在什么地方565.799987792969
来的呢?
采纳答案by LittleBobbyTables - Au Revtheitroad
I'm not sure what version you are using, but it sounds like this linkdescribes what you are experiencing.
我不确定您使用的是哪个版本,但听起来此链接描述了您所遇到的情况。
From the link:
从链接:
mysql> select * from aaa;
+----+------------+------+
| id | month_year | cost |
+----+------------+------+
| 1 | 2002-05-01 | 0.01 |
| 2 | 2002-06-01 | 1.65 |
| 3 | 2002-07-01 | 0.01 |
| 4 | 2002-01-01 | 0.01 |
+----+------------+------+
mysql> select id, sum(cost) from aaa group by id;
+----+---------------------+
| id | sum(cost) |
+----+---------------------+
| 1 | 0.00999999977648258 |
| 2 | 1.64999997615814 |
| 3 | 0.00999999977648258 |
| 4 | 0.00999999977648258 |
+----+---------------------+
The SUM function changes 0.01 to 0.00999999977648258.
Floating point numbers are stored as approximate values; if you are storing a price, you are better off using a decimal datatype which stores precise values.
浮点数存储为近似值;如果您要存储价格,最好使用存储精确值的十进制数据类型。