PHP rounding error

后端 未结 6 1195
伪装坚强ぢ
伪装坚强ぢ 2020-12-03 14:56

I\'m using PHP 5.2.13 on my linux server. I\'m getting weird error when rounding numbers. This is my test case:



        
6条回答
  •  独厮守ぢ
    2020-12-03 15:52

    The code in the answer of Shabbyrobe does not handle negative numbers. This is a working improvement of the code, which handles negative numbers as well as the default scale:

    function bcround($number, $scale = null) {
        if (is_null($scale)) {
            $scale = bcscale();
        }
        $fix = ($number < 0) ? '-' : '';
        $fix .= '0.' . str_repeat('0', $scale) . '5';
        $number = bcadd($number, $fix, $scale + 1);
        return bcdiv($number, "1.0", $scale);
    }
    

提交回复
热议问题