简体   繁体   English

如何在 PHP 中取整值?

[英]How to round up value in PHP?

I have a value like this:我有这样的价值:

$value = 2.3333333333;

and I want to round up this value into like this:我想把这个值四舍五入成这样:

$value = 2.35;

I already tried round, ceil and etc but the result is not what I expected.我已经尝试过 round、ceil 等,但结果不是我所期望的。

Please anyone help.请任何人帮忙。

Thanks谢谢

Taking your question literally, this will do it:从字面上看你的问题,这会做到:

$value = (round($original_value / 0.05, 0)) * 0.05

ie will round to the nearest 0.05.即将四舍五入到最接近的0.05。

If, for some reason, you want to always round up to 0.05, use如果出于某种原因,您希望始终四舍五入到 0.05,请使用

$value = (round(($original_value + 0.025) / 0.05, 0)) * 0.05

you have 3 possibility : round(), floor(), ceil()你有 3 种可能性:round()、floor()、ceil()

for you :给你:

$step = 2; // number of step 3th digit
$nbr = round(2.333333333 * $step, 1) / $step; // 2.35

$step = 4; // number of step on 3th digit
$nbr = round(2.333333333 * $step, 1) / $step; // 2.325

round圆形的

<?php
echo round(3.4);         // 3
echo round(3.5);         // 4
echo round(3.6);         // 4
echo round(3.6, 0);      // 4
    echo round(1.95583, 2);  // 1.96
echo round(1241757, -3); // 1242000
echo round(5.045, 2);    // 5.05
echo round(5.055, 2);    // 5.06
?>

floor地面

<?php
echo floor(4.3);   // 4
echo floor(9.999); // 9
echo floor(-3.14); // -4
?>

ceil细胞

<?php
echo ceil(4.3);    // 5
echo ceil(9.999);  // 10
echo ceil(-3.14);  // -3
?>

Complementary functions to round up / down to arbitrary number of decimals:补函数向上/向下舍入到任意小数位数:

/**
* Round up to specified number of decimal places
* @param float $float The number to round up
* @param int $dec How many decimals
*/
function roundup($float, $dec = 2){
    if ($dec == 0) {
        if ($float < 0) {
            return floor($float);
        } else {
            return ceil($float);
        }
    } else {
        $d = pow(10, $dec);
        if ($float < 0) {
            return floor($float * $d) / $d;
        } else {
            return ceil($float * $d) / $d;
        }
    }
}

/**
* Round down to specified number of decimal places
* @param float $float The number to round down
* @param int $dec How many decimals
*/
function rounddown($float, $dec = 2){
    if ($dec == 0) {
        if ($float < 0) {
            return ceil($float);
        } else {
            return floor($float);
        }
    } else {
        $d = pow(10, $dec);
        if ($float < 0) {
            return ceil($float * $d) / $d;
        } else {
            return floor($float * $d) / $d;
        }
    }
}

Try:尝试:

$value = 2.3333333333;
echo number_format($value, 2);

You can use this code:您可以使用此代码:

$value = 2.3333333333;
$value = round ( $value, 2, PHP_ROUND_HALF_UP);

best document is in here最好的文件在这里

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

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