在PHP中计算数字时的奇怪行为


strange behavior when calculating numbers in PHP

当我运行下面的PHP脚本时,它只是从11.5计算30%的折扣。我会得到一些奇怪的结果。通常情况下,在测试计算结果时,我希望条件为false。但相反,我明白了。

在这种情况下php有什么问题?

<?php
$_discount = 30;
$_price = 11.5;
$_qty = 1;
echo $_result = ((1-$_discount / 100) * $_price); // the result is 8.05 
echo $_result; // prints 8.05;
echo gettype($_result); // prints double
echo $_result !== 8.05; // returns 1 instead of 0
?>

尝试使用这个:

<?php
$_discount = 30;
$_price = 11.5;
$_qty = 1;
echo $_result = ((1-$_discount / 100) * $_price); // the result is 8.05 
echo $_result; // prints 8.05;
echo gettype($_result); // prints double
echo (double)$_result !== 8.05;
?>