简体   繁体   English

始终将小数舍入到指定的精度

[英]Always rounding decimals up to specified precision

I'm looking for an elegant way to rounding up decimal numbers always up. 我正在寻找一种优雅的方法来总是舍入十进制数。 Seems like round(0.0045001, 5, PHP_ROUND_HALF_UP); 好像round(0.0045001, 5, PHP_ROUND_HALF_UP); is not returning what I expected so I came up with following function; 没有返回我期望的结果,所以我想出了以下函数;

function roundUp($number, $precision) {
    $rounded = round($number, $precision);

    if ($rounded < $number) {
        $add = '0';
        for ($i = 1; $i <= $precision; $i++) {
            if ($i == 1) $add = '.';
            $add .= ($i == $precision) ? '1' : '0';
        }
        $add = (float) $add;
        $rounded = $rounded + $add;
    }

    return $rounded;
}

I was wondering if there is any other, more elegant way to achieve this? 我想知道是否还有其他更优雅的方法来实现这一目标?

Expected Result : var_dump(roundUp(0.0045001, 5)) // 0.00451; 预期结果: var_dump(roundUp(0.0045001, 5)) // 0.00451;

function roundup_prec($in,$prec)
{
    $fact = pow(10,$prec);
    return ceil($fact*$in)/$fact;
}

echo roundup_prec(0.00450001,4)."\n";
echo roundup_prec(0.00450001,5);

gives: 得到:

0.0046
0.00451
function roundUp($number, $precision) {
    $rounded = round($number, $precision);

    if ($rounded < $number) {
        $add = '0';
        for ($i = 1; $i <= $precision; $i++) {
            if ($i == 1) $add = '.';
            $add .= ($i == $precision) ? '1' : '0';
        }
        $add = (float) $add;
        $rounded = $rounded + $add;
    }

    return ceil($rounded);
}

Instead of ceil(x) you can also use (int)x , which gives the same result 除了ceil(x)您还可以使用(int)x ,得到相同的结果

EDIT: OK forget about that, I meant (int)x + 1 and thats not true for a number that's already rounded. 编辑:好的,算了吧,我的意思是(int)x + 1 ,而对于已经四舍五入的数字来说,那不是真的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM