Rio Eduardo
Rio Eduardo

Reputation: 185

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.

Please anyone help.

Thanks

Upvotes: 6

Views: 27529

Answers (5)

lubosdz
lubosdz

Reputation: 4500

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

Upvotes: 2

aya
aya

Reputation: 1613

You can use this code:

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

best document is in here

Upvotes: -2

Alban
Alban

Reputation: 3215

you have 3 possibility : 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
?>

Upvotes: 12

Bathsheba
Bathsheba

Reputation: 234715

Taking your question literally, this will do it:

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

i.e. will round to the nearest 0.05.

If, for some reason, you want to always round up to 0.05, use

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

Upvotes: 10

Nil&#39;z
Nil&#39;z

Reputation: 7475

Try:

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

Upvotes: -2

Related Questions