Round number to nearest fraction with PHP

E-mail
Written by Henrik, Saturday, 23 May 2009 Last Updated ( Saturday, 23 May 2009 14:36 )

Sometimes when you are trying to code small functions you realize that some one must have done the same thing before and you realize that google is as usual your friend in need!

I was trying to compile a helper function to round a float to what ever nearest fraction i needed. I found numerous examples on how to do this best while googleing.

After some time I found this article on how to round in PHP. It has a function posted by "Peter" which is pretty neat, you give a number and a fraction as decimal as arguments to the function and get the number rounded to it's nearest fraction return. Nice!

function roundToNearestFraction( $number, $fractionAsDecimal )
{
     $factor = 1 / $fractionAsDecimal;
     return round( $number * $factor ) / $factor;
}

// Round to nearest fifth
echo roundToNearestFraction( 3.78, 1/5 );

// Round to nearest third
echo roundToNearestFraction( 3.78, 1/3 );

Like this Joomla template?

As many other things on this site it is completely free! In collaboration with Midsjö AB are we releasing it into the public domain under the GNU/GPL version 2 license. You will find this template and other extensions under the Labs section then Joomla!. Good luck and happy Joomling!