MySQL 乘以浮点列:1*7.6 得到 7.599999904632568?
MySQL Multiplying float columns: 1*7.6 gives 7.599999904632568?
当我查询 SELECT 1*7.6
时,它给了我 7.6
但是当我进行列乘法时 (products.commision*sold.amount):
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
它给了我
ID | userid | date | idprod | amount | Category | Name | commision | fee
60 | 1 | 15-10-01 | 21 | 1 | Volish | Black | 7.6(float) | 7.599999904632568
为什么?
感谢您在评论中的帮助,
解决方案
浮点数是二进制,小数是...十进制,所以我将我的列更改为十进制(16,9)
在进行比较时,您必须将值类型转换为 integers/Decimals 而不是浮点数,因此
(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 and casting a floating to decimal in mysql
小数点将值设置为7位最大大小和2位最大精度的小数(12345.67)
编辑:我不确定将 CAST 添加到原始值或简单地转换诸如
之类的答案是否更有效
(products.commision * sold.amount ) as CAST(fee AS Decimal(7,2))
当我查询 SELECT 1*7.6
时,它给了我 7.6
但是当我进行列乘法时 (products.commision*sold.amount):
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
它给了我
ID | userid | date | idprod | amount | Category | Name | commision | fee
60 | 1 | 15-10-01 | 21 | 1 | Volish | Black | 7.6(float) | 7.599999904632568
为什么?
感谢您在评论中的帮助,
解决方案
浮点数是二进制,小数是...十进制,所以我将我的列更改为十进制(16,9)
在进行比较时,您必须将值类型转换为 integers/Decimals 而不是浮点数,因此
(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 and casting a floating to decimal in mysql
小数点将值设置为7位最大大小和2位最大精度的小数(12345.67)
编辑:我不确定将 CAST 添加到原始值或简单地转换诸如
之类的答案是否更有效(products.commision * sold.amount ) as CAST(fee AS Decimal(7,2))