1

Ok so I have a weird issue where I am running a query that in the select it is taking the result and multiplying that by 2000 i.e. 0.0025 * 2000 and giving me 4.9999888419121 or something when it should be 5. I have seen that there are issues with this but I have yet to find if there was a solution. I thought that math was like a basic computing function why would it fail in such a simple request as multiplication.

I am not sure that there is a fix for this, I really have been researching it but I figure that if anyone knew of one it would be here.

thanks again

example:

SELECT (table.rate * 2000) as per_ton ...

I have tried the + 0.0000 tricks and all without luck

4

1 回答 1

3

这个问题不是 MySQL 独有的。这是 IEEE 浮点表示的常见问题,它存储十进制值的近似值。(IEEE 浮点类型存储精确的 base 2 表示。)

因此,这不是乘法运算的“失败”。您为 rate 存储的值(显然)是 0.0025 的十进制值。这个值不能用 IEEE 浮点数精确表示,所以存储的是最接近的可能近似值。当该近似值乘以 2000 时,结果也是一个近似值,然后将其转换回十进制以进行显示。

“修复”是使用 DECIMAL 数据类型,而不是浮点类型,并且使用“大十进制”运算而不是浮点运算来执行乘法运算。

在进行乘法之前,您可以尝试通过将其转换回指定精度的小数来反转该近似值:

SELECT (CAST(table.rate AS DECIMAL(18,4) * 2000) AS per_ton ...

或者,您可以尝试使用 ROUND() 函数来修剪不需要的精度数字,例如

SELECT ROUND((table.rate * 2000),4) AS per_ton ...

这将使结果四舍五入到 5.0000

不过,真正的“修复”是使用 DECIMAL 数据类型定义列,并完全避免使用浮点列。

浮点值的这种行为有据可查,尽管在手册的末尾:

http://dev.mysql.com/doc/refman/5.1/en/problems-with-float.html

于 2012-08-09T16:16:11.763 回答