Rounding down numbers to set points with PHP -
i have basic 5 star rating system based on user submissions. depending on rating, particular image shown.
$user_rating
contains rating number 1 decimal place.
there 'star' images
0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5, 5.0
in file names.
i need whatever number contained in $user_rating rounded down nearest value above , stored in new variable $star_rating
. numbers can never rounded up. if $user_rating
4.9, $star_rating
should 4.5.
can me achieve this? thanks
edit - using returns original value - in case 3.8
$star_rating = $user_rating; function roundtohalf($star_rating) { $temp = $star_rating * 10; $remainder = $star_rating % 5; return ($temp - $remainder) / 10; }
function rounddowntohalf($number) { $remainder = ($number * 10) % 10; $half = $remainder >= 5 ? 0.5 : 0; $value = floatval(intval($number) + $half); return number_format($value, 1, '.', ''); } define("endl", "\n"); print rounddowntohalf(4.9) . endl; print rounddowntohalf(4.5) . endl; print rounddowntohalf(3.8) . endl; print rounddowntohalf(2.3) . endl; print rounddowntohalf(1.0) . endl; print rounddowntohalf(0.6) . endl;
output
4.5 4.5 3.5 2.0 1.0 0.5
all in 1 compact function:
function rounddowntohalf($n) { return number_format(floatval(intval($n)+((($n*10)%10)>=5?.5:0)),1,'.',''); }
Comments
Post a Comment