根据 PHP 中的分数四舍五入小数

Round up decimal number according to fraction in PHP

我正在努力将 excel 公式转换为 php 函数。现在我面临一个被四舍五入为分数的问题。请让我解释一下:

  • (2 * 18)/2.98 = 12.08 but according to my requirement it should be 12.25
    • (2 * 18.5)/2.98 = 12.416 but according to my requirement it should be 12.50
    • (2 * 18.8)/2.98 = 12.617 but according to my requirement it should be 12.75

在excel中,它是这样完成的:

  • ceiling(( 2 * 18 )/2.98, 0.25) = 12.25
    • ceiling(( 2 * 18.5 )/2.98, 0.25) = 12.50
    • ceiling(( 2 * 18.8 )/2.98, 0.25) = 12.75

我试过 PHP。 Ceil() 和 Floor() 不起作用,因为这 2 个应相应地给出输出 13 和 12。

另一轮 () 使用这些选项 PHP_ROUND_HALF_UP, PHP_ROUND_HALF_DOWN, PHP_ROUND_HALF_EVEN, or PHP_ROUND_HALF_ODD 没有达到目的。

有人帮我吗?

PHP 仅提供使用您找到的选项进行精确舍入的功能。但是,您可以通过一些创造性的数学和用户空间函数来完成与您想要的类似的事情。

尝试:

function roundTo($value, $roundTo = 1)
{
    $inverse = 1 / $roundTo;
    return round($value * $inverse) / $inverse;
}

参见:https://ideone.com/fojMrS

请注意,如果您想要 ceilfloor 功能,您必须为 ceilfloor 创建此功能的版本,这仅适用于round.

$YourNumber = 12.08;
$int = $YourNumber * 4;
$int = ceil($int);

echo $YourNumber ." was the start <br>";
echo $int / 4 ." is the answer";

使用这个功能:

function fractionRound($num,$frac) {
  return ceil($num/$frac)*$frac;
}

这样称呼它:

echo fractionRound(( 2 * 18 )/2.98, 0.25); 

它会四舍五入到最接近的 0.25 它会 return 12.25

function roundQuarters($input)
{
    $rm = $input % 0.25;
    return $rm == 0 ? $input : $input - $rm + 0.25;
}

这会将小数四舍五入到最接近的 0.25,如果它也是 0.25 的约数,则 return 相同。简单。

您可以将 0.25 替换为您想要的任何小数,甚至可以对其进行参数化。