1

I have a basic 5 star rating system based on user submissions. depending on the rating, a particular image is shown.

$user_rating contains the rating number to one decimal place.

There are 'star' images with

0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5, 5.0

in the file names.

I need whatever number is contained in $user_rating to be rounded down to the nearest value above and stored in a new variable $star_rating. The numbers can never be rounded up. Even if $user_rating is 4.9, $star_rating should be 4.5.

Can someone help me achieve this? Thanks

EDIT - using this but just returns original value - in this case 3.8

$star_rating = $user_rating;


 function roundToHalf($star_rating) {
     $temp = $star_rating * 10;
     $remainder = $star_rating % 5;
     return ($temp - $remainder) / 10;
 }
4

4 回答 4

3
<?php

function roundRating($rating, array $ratings)
{
  if (in_array($rating, $ratings))
  {
    return $rating;
  }

  foreach($ratings as $key => $value)
  {
    if ($value > $rating)
    {
      return $ratings[($key - 1)];
    }   
  }
  return FALSE;
}

$ratings = array(0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5, 5.0);
$rating = 4.3;

if ($rate = roundRating($rating, $ratings))
  echo sprintf('%.01f', $rate);

Demo: http://3v4l.org/BRBne

于 2013-08-19T21:08:42.447 回答
2

A simple approach:

function roundToHalf($star_rating) {
    return floor( $star_rating * 2 ) / 2;
}

This works because you're looking values evenly divisible by .5 . The result is a float. I think you're better off getting back a numerical value, in case you want to use it for mathematical purposes. Let your display code format it as needed.

于 2013-08-19T21:13:32.220 回答
1

Multiply by 10 to make it into an integer than use the modulus operator '%' to remove the remainder. Then divide by 10 to make it back into a decimal.

 function roundToHalf($number) {
     $temp = intval($number * 10);
     $remainder = $temp % 5;
     return ($temp - $remainder) / 10;
 }
于 2013-08-19T20:50:25.550 回答
1
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 one compact function:

function roundDownToHalf($n) {
  return number_format(floatval(intval($n)+((($n*10)%10)>=5?.5:0)),1,'.','');
}
于 2013-08-19T21:03:38.297 回答