Tuesday, May 3, 2011

round number to nearest 0.2 with PHP

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...

From stackoverflow
  • round(3.78 * 5) / 5 = 3.8
    
    peirix : awesome! I knew there had to be an easy solution to this. Thanks (:
  • function round2($original) {
        $times5 = $original * 5;
        return round($times5) / 5;
    }
    
  • 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)

    nickf : +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.
  • 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 );
    
    Alix Axel : Elegant, but you are missing some "$".
    peirix : 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 (:

0 comments:

Post a Comment