How can I make sure a float will always be rounded up with PHP?

前端 未结 5 613
野趣味
野趣味 2020-12-09 08:33

I want to make sure a float in PHP is rounded up if any decimal is present, without worrying about mathematical rounding rules. This function would work as follows:

5条回答
  •  -上瘾入骨i
    2020-12-09 08:57

    I know this is an old topic, however it appears in Google. I will extend Blake Plumb's answer regarding precision.

    ceil(1024.321 * 100) / 100;
    

    Multiplying by 100 and dividing by 100 only works with one-hundredths. This isn't accurate on tenths, one-thousandths, one-hundred thousandths, etc.

    function round_up($number, $precision = 2)
    {
        $fig = pow(10, $precision);
        return (ceil($number * $fig) / $fig);
    }
    

    Results:

    var_dump(round_up(1024.654321, 0)); // Output: float(1025)
    var_dump(round_up(1024.654321, 1)); // Output: float(1024.7)
    var_dump(round_up(1024.654321, 2)); // Output: float(1024.66)
    var_dump(round_up(1024.654321, 3)); // Output: float(1024.655)
    var_dump(round_up(1024.654321, 4)); // Output: float(1024.6544)
    var_dump(round_up(1024.654321, 5)); // Output: float(1024.65433)
    var_dump(round_up(1024.654321, 6)); // Output: float(1024.654321)
    

    Notes:

    Thanks for the contributions from Joseph McDermott and brandom for improving my original snippet.

提交回复
热议问题