php - ceil() 函数的奇怪工作 (php)

标签 php ceil

这段代码:

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/

相关文章:

php - 各种公共(public)网站之间的单点登录架构是什么?

mysql - Excel 到 SQL - CEILING 和错误代码 1582

scala - 如果它不是整数,如何四舍五入?

python - 将日期时间限制为下一刻钟

php - Mysql Php 使用事务和提交一次选择和处理一条记录

javascript - 在 PHP 类中加载外部 js 文件

php - 使用 PHPSpreadsheet 打开受密码保护的 XLSX 文件

java - TreeMap java中的天花板和地板

Swift 相当于 CGFloat 的 ceilf

php - 从输入文本创建标签云的最佳方法