How to round to the nearest ten in PHP?

3

I saw this question here in Stack Overflow How to round to the nearest ten? and found it very interesting.

Only the question is about JavaScript.

How could I round off a number to the nearest ten in PHP?

Example:

11  => 20
23  => 30,
2.5 => 10
    
asked by anonymous 18.10.2015 / 23:32

2 answers

7

Would you like to leave numbers from 0 always in tens? If yes, see if this example helps:

$num = 11;
$num = ceil($num / 10) * 10;
    
18.10.2015 / 23:44
2

What I use here is:

function roundByValue($valor, $valorArredondamento){
    if($valorArredondamento != 0){
        $valor = round($valor/$valorArredondamento)*$valorArredondamento;
    }
    return $valor;
}

// pr = print_r
pr(roundByValue(10.5, 1));      // 11
pr(roundByValue(10.23, 0.5));   // 10
pr(roundByValue(10.27, 0.5));   // 10.5
pr(roundByValue(10.07, 0.25));  // 10
pr(roundByValue(10.74, 0.10));  // 10.7
pr(roundByValue(10.17, 0.75));  // 10.5
    
19.10.2015 / 14:53