'How to round up to the next even number?

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


Solution 1:[1]

$num = ceil($input); // Round up Floats to an integer
$num += $num % 2; // add $num modulo 2 remainder (is 1 if odd, 0 if even)

More options:

$num += $num % 2;       //next even
$num -= $num % 2;       //prev even
$num += ($num + 1) % 2; //next odd
$num -= ($num + 1) % 2; //prev odd

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1