Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to round up to the next even number?

Tags:

php

rounding

I want to round up to the next even whole number, with php.

Example:

  • if 71 -> round up to 72
  • if 33.1 -> round up to 34
  • if 20.8 -> round up to 22
like image 825
Levchik Avatar asked Dec 18 '15 20:12

Levchik


1 Answers

$num = ceil($input); // Round up decimals to an integer
if($num % 2 == 1) $num++; // If odd, add one

Test cases:

$tests = ['71' => '72', '33.1' => '34', '20.8' => '22'];
foreach($tests as $test => $expected) {
    $num = ceil($test);
    if($num % 2 == 1) $num++;
    echo "Expected: $expected, Actual: $num\n";
}

Produces:

Expected: 72, Actual: 72
Expected: 34, Actual: 34
Expected: 22, Actual: 22
like image 178
nickb Avatar answered Oct 13 '22 08:10

nickb