How to round to the nearest ten in PHP?

Asked

Viewed 1,125 times

3

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

Only that the question is Javascript.

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

Example:

11  => 20
23  => 30,
2.5 => 10

2 answers

7


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

$num = 11;
$num = ceil($num / 10) * 10;
  • Help yes, exactly that. Just use it in a function and it’s good!

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
  • This second parameter is to define whether to round up or down?

  • Actually no, it’s to define the rounding multiplier, for example, I want to round each 0.25, or each 0.5, so it rounds to the nearest number of the rounding multiplier.

  • So it’s almost what I said, if you understand what I mean by "down" and "up"

  • Not because, as I commented is the multiplier, in an example roundByValue(10.27, 0.5) the result will be 10.5, for the multiplier is 0.5, already in roundByValue(10.27, 0.15) the result will be 10.3 for the multiplier is 0.15.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.