Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
899 views
in Technique[技术] by (71.8m points)

mysql - Using SUM on FLOAT data

One table:
items(id, price)

Has one row:
id: 1, price: 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.

Where does the 565.799987792969 come from?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I'm not sure what version you are using, but it sounds like this link describes 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...