在MySQL内部对小数进行精度数学运算时,它将字符串处理为Float而不是固定,例如,如果我们在数据库中有以下列(数量类型为DECIMAL(43,20)
)
+--------------------------+
| amount |
+--------------------------+
| 0.20000000000000000000 |
+--------------------------+
运行以下PHP代码
$amount_to_add = "0.1";
$stmt = $dbh->prepare("UPDATE table SET amount = amount + :amount");
$stmt->bindValue("amount", $amount_to_add);
$stmt->execute();
会导致:
+--------------------------+
| amount |
+--------------------------+
| 0.30000000000000004000 |
+--------------------------+
注意额外的0.0000000000000000 4000
因为$amount_to_add
是字符串
由于我需要使用BC Math函数,因此其输出始终为字符串
And i can't convert it to double/float inside PHP because it will lose precision and decimal points
我应该如何将它传递给MySQL以将其视为十进制(固定)而不是字符串(浮点数),它不需要在PHP中更改字符串类型?
是否可以在运行查询时声明数据类型?所以它在MySQL中将字符串更改为十进制
答案 0 :(得分:5)
UPDATE table SET amount = amount + CAST(:amount AS DECIMAL(X, Y))