如何围绕下一个偶数?

时间:2015-12-18 20:33:40

标签: php rounding

我希望使用php来整理下一个整数。

示例:

  • 如果71 - >最高为72
  • 如果33.1 - >最高为34
  • 如果20.8 - >最高为22

1 个答案:

答案 0 :(得分:9)

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

测试用例:

$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