简体   繁体   English

PHP Round 函数 - 最多舍入 2 dp?

[英]PHP Round function - round up to 2 dp?

In PHP how would i round up the value 22.04496 so that it becomes 22.05?在 PHP 中,我如何将值 22.04496 舍入以使其变为 22.05? It seems that round(22.04496,2) = 22.04.似乎round(22.04496,2) = 22.04。 Should it not be 22.05??不应该是22.05吗?

Thanks in advance提前致谢

you can do it using ceil and multiplying and dividing by a power of 10.您可以使用 ceil 并乘以和除以 10 的幂来做到这一点。

echo ceil( 1.012345 * 1000)/1000;

1.013

Do not do multiplication inside a ceil, floor or round function!不要在 ceil、floor 或 round 函数内进行乘法运算! 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 .例如ceiling(2.2200001, 2)将给出2.23

Based on comments I've also added my floor function as this has similar problems:根据评论,我还添加了我的floor功能,因为这有类似的问题:

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);
}

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!

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 PHP 的 round 函数可以处理一个附加参数,该参数控制如何进行舍入: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

It's not working well.它运作不佳。

round(1.211,2,PHP_ROUND_HALF_UP); 
// Res: 1.21

My Solution:我的解决方案:

$number = 1.211;

echo myCeil($number,2);

function myCeil($number,$precision = 0){
    $pow = pow(10,$precision);
    $res = (int)($number * $pow) / $pow;
    
    if($number > $res){
        $res += 1 / $pow;
    }
    return $res;
}
// Res 1.22

Why should it be 22.05 ?为什么应该是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第三位小数小于 5 ,因此当您将其四舍五入为 2 小数精度时,它会向下舍入为22.04

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

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