Domanda

I have table column that have positive and negative float digits. When I do query to get SUM() of all digits, it's returns wrong result.

Table:

+----+---------+--------+
| id | user_id | points |
+----+---------+--------+
|  1 |      38 | 30.5   |
|  2 |      38 | -5.3   |
+----+---------+--------+

Query:

SELECT SUM(points) FROM table WHERE user_id=38

Result:

25.199999809265137

Why is this happening? Why I don't get 25.2 as the result?

È stato utile?

Soluzione

As documented under Problems with Floating-Point Values:

Floating-point numbers sometimes cause confusion because they are approximate and not stored as exact values. A floating-point value as written in an SQL statement may not be the same as the value represented internally.

Altri suggerimenti

I'm guessing your points field is a float, which is not exact.

"Approximate value" According to the mysql dcoumentation.

Use decimal or numeric types to make exact calcuations with a known amount of numbers behind the decimal point.

Or round the result of your query on 1 digit, because your sources are also 1 digit behind the decimal point. But know that it's rounded and exact comaprison is not possible (better: not 100% exact and predictable)

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top