echo 'For the month of January-2019';
echo'<hr>';
echo $basicValue = floor((250000 / 31) * 31);
echo '<br>';
echo $allowance = (30000 / 31) * 31;
echo '<br>';
echo $house_rent=floor($allowance);
echo'<hr>';
echo 'For the month of February-2019';
echo'<hr>';
echo $basicValue = floor((250000 / 28) * 28);
echo '<br>';
echo $allowance = (30000 / 28) * 28;
echo '<br>';
echo $house_rent=floor($allowance); // This is return 29999 that is wrong???
这是因为$allowance
是一个浮点数,而floor
正在返回一个int。
对于您的预期结果,我建议使用round()
来围绕float
值。
http://php.net/manual/ro/function.round.php
输出:
echo 'For the month of January-2019';
echo "\n";
echo $basicValue = floor((250000 / 31) * 31);
echo "\n";
echo $allowance = (30000 / 31) * 31;
echo "\n";
var_dump($allowance);
$allowance = intval($allowance);
echo "\n";
var_dump($allowance);
echo "\n";
echo $house_rent=floor($allowance);
echo "\n";
echo 'For the month of February-2019';
echo "\n";
echo $basicValue = floor((250000 / 28) * 28);
echo "\n";
echo $allowance = (30000 / 28) * 28;
echo "\n";
var_dump($allowance);
$allowance = intval($allowance);
echo "\n";
var_dump($allowance);
echo $house_rent=floor($allowance); // This is return 29999 that is wrong???
是:
For the month of January-2019
250000
30000
float(30000)
int(30000)
30000
For the month of February-2019
250000
30000
float(30000)
int(29999)
29999
30000 / 28
的值不是整数,也不能完全表示。发生小的舍入错误。计算机中表示的值略小于表达式的精确数学值。当乘以28
时,结果略小于30000
并且floor()
执行它应该做的事情:忽略小数部分并仅返回29999
的整数部分。
在计算机中表示的30000 / 28 * 28
的值约为29999.9999999999963620211929082870
。
阅读有关浮点表示的更多信息以及使用它可能遇到的问题:https://floating-point-gui.de/
这不是PHP或计算机中数字的浮点表示的问题。这也是在现实生活中发生的事情。
我们通常认为1/3
是0.333333333333333...
,但无论我们在小数点后面加了多少3
,乘以3
都不会产生正确的1
。