Round number to the nearest 0.2 with PHP

I create this rating system using 5x stars. And I want the title to include an average rating. So I created stars showing 1 / 5th. Using "1.2", I get a full star and one point on the next star and so on ...

But I did not find a good way to round to the nearest .2 ... I decided that I could multiply by 10, then round, and then start the switch in round 1 to 2, 3 to 4 and so on. But it seems tedious and unnecessary ...

+6
math php rounding
source share
5 answers
round(3.78 * 5) / 5 = 3.8 
+27
source share

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 ); 
+18
source share
 function round2($original) { $times5 = $original * 5; return round($times5) / 5; } 
+4
source share

So, your total is 25, is it possible to use floats and use 1-> 25/25? Thus, less computation is required ... (if at all)

+3
source share

Why does everyone provide solutions that require deeper control or transformation? Want 0.2? Then:

 round($n / 0.2) * 0.2; // $n = 3.78 / 0.2 = 18.9 (=) 19 * 0.2 = 3.8 // 

Do you want 5? Then:

 round($n / 5) * 5; // $n = 17 / 5 = 3.4 (=) 3 * 5 = 15 // 

It is so simple.

+1
source share

All Articles