我对在 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
它返回 8.55,这是记录中写入的正确数字,所以我期望第一个查询返回 3.45。
表“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
类型的比较是一个坏主意,但每个人都忘记了它。
关于MySQL轮询,结果错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41484223/