四舍五入到小数点后两位,但如果非常接近,则将其设置为最接近的整数

Round correct to 2 decimal places but if very close, set it to nearest integer

仅当数字非常接近时,是否存在将数字四舍五入为最接近的整数值的函数或可能性。例如:

$var = 18.99;
$res = round($var, 2); // output: 18.99, expected - 19

我试过不带第二个参数的 round,但是 18.65 会失败。

$var = 18.99;
$res = round($var); //output - 19

$var = 18.65;
$res = round($var); //output - 19, expected 18.65

我只是想让 .9 范围将其自身转换为下一个 int 值。这可能吗?

这基本上是将任何值四舍五入为最接近的整数,然后检查两者与极限的差异。

function nearly_round($value, $limit = 0.1) { 
    $rounded = round($value); 
    //Check the difference. If less than the limit, 
    //return the rounded value, else the original number.
    return abs($rounded - $value) < $limit ? $rounded : $value; 
}

echo nearly_round(-0.9); // -1
echo nearly_round(-0.8); // -0.8
echo nearly_round(0.8);  // 0.8
echo nearly_round(0.9);  // 1