MySQL 轮询,结果错误

MySQL round in query, wrong result

我对 运行 在 MySQL 服务器 (v5.5.50-0+deb8u1) 上进行的查询有疑问。

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

所以金额值为 12 - 8,5500000000000007 = 3.4499999999999993

但是如果我 运行 查询:

 SELECT qty FROM Table WHERE id = 5213

它 returns 8.55 是记录中写入的正确数字,所以我期待第一个查询返回 3.45。

table "Table" 中的 "qty" 列是 DOUBLE。

怎么可能?我怎样才能从查询中得到正确的答案? 提前致谢

那是 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.

这一说法也适用于许多编程语言。有些数字甚至没有准确的表示。这是来自 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

所以简而言之,通常做 float1 = float2 类型的比较是一个坏主意,但每个人都忘记了它。

您可以将 'qty' 列定义为 decimal(10,2)