MySQL round in query, wrong result

百般思念 提交于 2019-12-25 09:19:15

问题


I have a question about a query that I'm running on a MySQL Server (v5.5.50-0+deb8u1).

SELECT 12 - (SELECT qty FROM Table WHERE id = 5213) AS Amount

so Amount value is 12 - 8,5500000000000007 = 3.4499999999999993

But if I run the query:

 SELECT qty FROM Table WHERE id = 5213

it returns 8.55 that is the correct number written in the record, so I was expecting that the first querty returned 3.45.

The "qty" column in the table "Table" is a DOUBLE.

How is it possibile? How can I get the right answer from the query? thanks in advance


回答1:


Well that's just the way floating numbers are.

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.

This statement holds true for many programming languages as well. Some numbers don't even have an exact representation. Here's something from the python manual

The problem is easier to understand at first in base 10. Consider the fraction 1/3. You can approximate that as a base 10 fraction:

0.3 or, better,

0.33 or, better,

0.333 and so on. No matter how many digits you’re willing to write down, the result will never be exactly 1/3, but will be an increasingly better approximation of 1/3.

In the same way, no matter how many base 2 digits you’re willing to use, the decimal value 0.1 cannot be represented exactly as a base 2 fraction. In base 2, 1/10 is the infinitely repeating fraction

So in short generally doing is float1 = float2 type of comparison is a bad idea but everyone keeps forgetting it.




回答2:


You can define 'qty' column as decimal(10,2)



来源:https://stackoverflow.com/questions/41484223/mysql-round-in-query-wrong-result

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!