jitendrapurohit jitendrapurohit - 16 days ago 8
PHP Question

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

Is there any function or possibility where the number is round to a nearest integer value ONLY if the number is very close. Eg:

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


I've tried with round without second param, but that will fail for 18.65.

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

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


I just wanted the
.9
range to convert itselt to the next int value. Is this possible ?

Answer

This basically rounds any value to nearest integer and then checks the difference of the two with the limit.

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
Comments