关于浮动精度:MySQL Multiplying浮动列:1 * 7.6给出7.599999904632568?

MySQL Multiplying float columns: 1*7.6 gives 7.599999904632568?

当我查询SELECT 1*7.6时,它把我引到7.6上。

但当我进行列乘法时(products.commission*seld.amount):

1
2
3
4
5
6
7
8
SELECT *,
(products.commision*sold.amount) as fee
FROM sold
RIGHT JOIN products
ON sold.idprod=products.ID
AND DATE(sold.date) BETWEEN DATE('2015-10-01') AND DATE('2015-10-31')
WHERE sold.userid="1"
ORDER BY sold.userid

它使我感到难受

1
2
ID | userid | date     | idprod | amount | Category | Name  | commision  | fee
60 | 1      | 15-10-01 | 21     | 1      | Volish   | Black | 7.6(float) | 7.599999904632568

为什么?


当进行比较时,您必须将值类型转换为整数/小数,而不是浮点值。

1
(CAST(products.commision AS Decimal(7,2)) * CAST(sold.amount AS Decimal(7,2))) as fee

来自https://dev.mysql.com/doc/refman/5.0/en/cast-functions.html并在mysql中将浮点转换为十进制

十进制将值设置为十进制,其中7位为最大大小,2位为最大精度(12345.67)。

编辑:我不确定将强制转换添加到原始值或简单地强制转换答案是否更有效,例如

1
(products.commision  * sold.amount ) as CAST(fee AS Decimal(7,2))


感谢您的评论帮助,

解决方案

浮点是二进制的,小数是…十进制,所以我把列改为十进制(16,9)