While working with currency calculations, we often require to round a number to the nearest 10 or the nearest 50, like 407 should be 410.

I've written a function which will do exactly that, it requires two parameters the number to the round, and the integer to be rounded to. The function is like MROUND found in MS Excel & OpenOffice Spreadsheet.

Example:

Output:

I've written a function which will do exactly that, it requires two parameters the number to the round, and the integer to be rounded to. The function is like MROUND found in MS Excel & OpenOffice Spreadsheet.

Code: PHP

function roundToNearest($number,$nearest=50)

{

$number = round($number);

if($nearest>$number || $nearest <= 0)

return $number;

$x = ($number%$nearest);

return ($x<($nearest/2))?$number-$x:$number+($nearest-$x);

}

Code: PHP

print roundToNearest(25.60,10)."<br/>";

print roundToNearest(2560,50)."<br/>";

print roundToNearest(2575,50)."<br/>";

Code:

30 2550 2600