【问题标题】:PHP floor returns two diffent resutl when formula is same?当公式相同时,PHP floor 返回两个不同的结果?
【发布时间】:2019-03-06 05:38:42
【问题描述】:
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.net/ + floor = php.net/floor: Returns the next lowest integer value (as float) by rounding down value if necessary.

标签: php division multiplication floor


【解决方案1】:

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

为了您的预期结果,我建议使用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

【讨论】:

    【解决方案2】:

    30000 / 28 的值不是整数,不能精确表示。出现一个小的舍入误差。计算机中表示的值略小于表达式的精确数学值。当乘以28 时,结果略小于30000 并且floor() 做了它应该做的事情:忽略小数部分并只返回整数部分29999

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

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


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

    我们通常认为1/30.333333333333333...,但无论我们在小数点后放置多少个3,乘以3 并不能完全生成1

    【讨论】:

      猜你喜欢
      • 2012-09-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多