Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

round number to nearest 0.2 with PHP

Tags:

php

math

rounding

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

like image 896
peirix Avatar asked Apr 28 '09 06:04

peirix


3 Answers

round(3.78 * 5) / 5 = 3.8
like image 69
Georg Schölly Avatar answered Oct 21 '22 04:10

Georg Schölly


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 );
like image 41
Peter Bailey Avatar answered Oct 21 '22 03:10

Peter Bailey


function round2($original) {
    $times5 = $original * 5;
    return round($times5) / 5;
}
like image 35
Randy Sugianto 'Yuku' Avatar answered Oct 21 '22 03:10

Randy Sugianto 'Yuku'