tags:

views:

900

answers:

4

I'm creating this rating system using 5-edged stars. And I want the heading to include the average rating. So I've created stars showing 1/5ths. Using "1.2" I'll get a full star and one point on the next star and so on...

But I haven't found a good way to round up to the closest .2... I figured I could multiply by 10, then round of, and then run a switch to round 1 up to 2, 3 up to 4 and so on. But that seems tedious and unnecessary...

+21  A: 
round(3.78 * 5) / 5 = 3.8
Georg
awesome! I knew there had to be an easy solution to this. Thanks (:
peirix
+4  A: 
function round2($original) {
    $times5 = $original * 5;
    return round($times5) / 5;
}
yuku
+3  A: 

So your total is 25, would it be possible to not use floats and use 1->25/25? That way there is less calculations needed... (if any at all)

JH
+1 - that's a good point, but I'm assuming that the score of 1.2 or 1.17 or whatever is actually an average, so there'll be fractions involved at some point anyway.
nickf
+11  A: 

A flexible solution

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 );
Peter Bailey
Elegant, but you are missing some "$".
Alix Axel
Nice. But since I know that I'll always be needing fraction of 5, there is really no point in creating a general function for it. But I'll def. keep this in mind. Thanks (:
peirix