Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP's equivalent to Excel's MROUND function, rounding to nearest multiple

Excel has the MROUND function which rounds a number up/down to a given multiple.

=MROUND(600, 400) //--> 800
=MROUND(14,4)     //--> 16
=MROUND(0.5,2)    //--> 0

What is the equivalent function for PHP?

If there is none, how would you do it?

like image 733
ShadowScripter Avatar asked Jun 08 '12 13:06

ShadowScripter


1 Answers

You can achieve the same effect by dividing by the denominator, rounding it, then multiplying it again by the denominator. Eg:

function roundTo($number, $to)
{
    return round($number/$to, 0)* $to;
}

echo roundTo(87.23, 20); //80

echo roundTo(600, 400) // 800
echo roundTo(14,4)     // 16
echo roundTo(0.5,2)    // 0
like image 102
Nasser Hekmati Avatar answered Nov 14 '22 23:11

Nasser Hekmati