PHP round half up doesn't work

前端 未结 3 546
梦毁少年i
梦毁少年i 2021-01-25 19:40

I have this code


I want to round two decimals to half up, I expect a value as 0.58... but

相关标签:
3条回答
  • 2021-01-25 20:27

    if you expect 0,58 you don't have to use a "half round" but the ceil function

    $v = 0.575;
    echo ceil($v * 100) / 100; // show 0,58
    
    0 讨论(0)
  • 2021-01-25 20:29

    The value 0.572 can not be rounded up to 0.58, because the third decimal, 2, is less than half (or 5). If you were doing round(0.575, 2, PHP_ROUND_HALF_UP) you would get 0.58. In this case 0.57 is the correct rounded value.

    If you wish to always round up from the 3rd decimal, regardless of its value you could use ciel() instead, but it requires a little additional math. A simple function to demonstrate rounding up always would be...

    function forceRoundUp($value, $decimals)
    {
        $ord = pow(10, $decimals);
        return ceil($value * $ord) / $ord;
    }
    
    echo forceRoundUp(0.572, 2); // 0.58
    echo forceRoundUp(0.57321, 4); // 0.5733
    
    0 讨论(0)
  • 2021-01-25 20:29
    function round_up($value, $places)
    {
      $mult = pow(10, abs($places));
      return $places < 0 ?
      ceil($value / $mult) * $mult :
      ceil($value * $mult) / $mult;
    }
    
    echo round_up(0.572,2);
    

    Hope this will work for you!!

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