PHP round half up doesn't work

前端 未结 3 598
梦毁少年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: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
    

提交回复
热议问题