对于这段代码:
$value = 200.1;
$denominator = 0.1;
echo "value: $value\n";
echo "denominator: $denominator\n";
$resultInt = ($value / $denominator);
echo "($value / $denominator) = ";
printf ("%f\n", $resultInt);
$resultInt = (int) ($value / $denominator);
echo "(int) ($value / $denominator) = ";
printf ("%f\n", $resultInt);
$resultInt = floor($value / $denominator);
echo "floor($value / $denominator) = ";
printf ("%f\n", $resultInt);
$resultInt = floor((int) ($value / $denominator));
echo "floor((int) ($value / $denominator)) = ";
printf ("%f\n", $resultInt);
$resultInt = floor((float) 2001);
echo "floor((float) 2001) = ";
printf ("%f\n", $resultInt);
$resultInt = round($value / $denominator, PHP_ROUND_HALF_DOWN);
echo "round($value / $denominator, PHP_ROUND_HALF_DOWN) = ";
printf ("%f\n", $resultInt);
$valueMul = $resultInt * $denominator;
if ($valueMul !== $value) {
echo "they are not the same\n";
var_dump($value);
var_dump($valueMul);
}
$valueDiff = $value - $valueMul;
if ($valueDiff !== 0) {
echo "valueDiff is not zero\n";
var_dump($valueDiff);
}
我有这个结果:
value: 200.1
denominator: 0.1
(200.1 / 0.1) = 2001.000000
(int) (200.1 / 0.1) = 2000.000000
floor(200.1 / 0.1) = 2000.000000
floor((int) (200.1 / 0.1)) = 2000.000000
floor((float) 2001) = 2001.000000
round(200.1 / 0.1, PHP_ROUND_HALF_DOWN) = 2001.000000
they are not the same
float(200.1)
float(200.1)
valueDiff is not zero
float(-2.8421709430404E-14)
上述所有计算的预期结果是 2001,但在某些情况下它是 2000。
我知道由于计算机在二进制上运行,因此分数不会以小数形式存储在变量中。
但正如地板手册所述:
地板 -向下舍入分数
因此我期望得到与以下相同的结果:
round(200.1 / 0.1, PHP_ROUND_HALF_DOWN)
但 round 按预期返回 2001,而下限返回 2000(错误)。
你知道为什么吗?
我还发现这var_debug
是不一致的:
慕斯王