当公式相同时,PHP楼层返回两个不同的结果?

问题描述 投票:1回答:2
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???
php division multiplication floor
2个回答
2
投票

这是因为$allowance是一个浮点数,而floor正在返回一个int。

对于您的预期结果,我建议使用round()来围绕float值。

http://php.net/manual/ro/function.round.php

见:https://3v4l.org/skrQC

输出:

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

0
投票

30000 / 28的值不是整数,也不能完全表示。发生小的舍入错误。计算机中表示的值略小于表达式的精确数学值。当乘以28时,结果略小于30000并且floor()执行它应该做的事情:忽略小数部分并仅返回29999的整数部分。

在计算机中表示的30000 / 28 * 28的值约为29999.9999999999963620211929082870

阅读有关浮点表示的更多信息以及使用它可能遇到的问题:https://floating-point-gui.de/


这不是PHP或计算机中数字的浮点表示的问题。这也是在现实生活中发生的事情。

我们通常认为1/30.333333333333333...,但无论我们在小数点后面加了多少3,乘以3都不会产生正确的1

© www.soinside.com 2019 - 2024. All rights reserved.