这段代码:
echo (40 * (10 / 100 + 1)); //44
echo (50 * (10 / 100 + 1)); //55
echo ceil(40 * ((10 / 100) + 1)); //44
echo ceil(50 * ((10 / 100) + 1)); //56 (!)
我认为,“56”是 float (55.0000000001 => 56),但我不明白为什么“40”的结果是“44”,而不是“45”
最佳答案
55 实际上不是 55。您可以轻松验证:
<?php
$x = (40 * (10 / 100 + 1)); // 44
$y = (50 * (10 / 100 + 1)); // 55
echo '$x == 44: ' . ($x == 44 ? 'True' : 'False') . "\n";
echo '$y == 55: ' . ($y == 55 ? 'True' : 'False') . "\n";
echo '$y > 55: ' . ($y > 55 ? 'True' : 'False') . "\n";
echo $y - 55;
产量:
$x == 44: True
$y == 55: False
$y > 55: True
7.105427357601E-15
如您所见,差异很小 (7.1 * 10^-15),但仍然大于 55,因此 ceil
会将其四舍五入。
你刚刚看到 55
的原因是因为回显它会转换 float into a string :
String conversion is automatically done in the scope of an expression where a string is needed. This happens when using the echo or print functions, or when a variable is compared to a string.
对于此转换,标准截断行为会在某个点截断数字。这是由 precision
configuration parameter 配置的并默认为 14。您可以通过使用具有自定义精度的 sprintf
来避免此行为:
echo sprintf('%.50f', $y);
// 55.00000000000000710542735760100185871124267578125000
关于php - ceil() 函数的奇怪工作 (php),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33296114/