PHP Round function - round up to 2 dp?

前端 未结 5 949
孤街浪徒
孤街浪徒 2020-12-21 02:38

In PHP how would i round up the value 22.04496 so that it becomes 22.05? It seems that round(22.04496,2) = 22.04. Should it not be 22.05??

Thanks in advance

相关标签:
5条回答
  • 2020-12-21 03:00

    I think the best way:

    echo ceil(round($value * 100)) / 100;
    

    Example:

    $value = 77.4;
    echo ceil($value * 100) / 100; // 77.41 - WRONG!
    echo ceil(round($value * 100)) / 100; // 77.4 - OK!
    
    0 讨论(0)
  • 2020-12-21 03:06

    you can do it using ceil and multiplying and dividing by a power of 10.

    echo ceil( 1.012345 * 1000)/1000;
    
    1.013
    
    0 讨论(0)
  • 2020-12-21 03:10

    Do not do multiplication inside a ceil, floor or round function! You'll get floating point errors and it can be extremely unpredictable. To avoid this do:

    function ceiling($value, $precision = 0) {
        $offset = 0.5;
        if ($precision !== 0)
            $offset /= pow(10, $precision);
        $final = round($value + $offset, $precision, PHP_ROUND_HALF_DOWN);
        return ($final == -0 ? 0 : $final);
    }
    

    For example ceiling(2.2200001, 2) will give 2.23.

    Based on comments I've also added my floor function as this has similar problems:

    function flooring($value, $precision = 0) {
        $offset = -0.5;
        if ($precision !== 0)
            $offset /= pow(10, $precision);
        $final = round($value + $offset, $precision, PHP_ROUND_HALF_UP);
        return ($final == -0 ? 0 : $final);
    }
    
    0 讨论(0)
  • 2020-12-21 03:16

    The round function of PHP can handle an additional argument, which controls how the rounding is done: http://php.net/manual/en/function.round.php

    Examples from the link:

    echo round(9.5, 0, PHP_ROUND_HALF_UP);   // 10
    echo round(9.5, 0, PHP_ROUND_HALF_DOWN); // 9
    echo round(9.5, 0, PHP_ROUND_HALF_EVEN); // 10
    echo round(9.5, 0, PHP_ROUND_HALF_ODD);  // 9
    
    0 讨论(0)
  • 2020-12-21 03:21

    Why should it be 22.05? The third decimal is less than 5, hence when you round it to 2 decimal precision it's rounded down to 22.04

    0 讨论(0)
提交回复
热议问题