开发者

Convert Fraction to Percent

In our Learning Management System someone in their infinite wisdom decided to keep non-standardized grades. As a result we have a table similar to this:

  • Assignment 1 - 100
  • Assignment 2 - 80
  • Assignment 3 - 10/20
  • Assignment 4 - 68
  • Assignment 5 - 8/10

As you can see we have a mixture of percentages and fractions. What i'd like to do is check if the grade is a fraction i.e. 10/20 and if so convert it out to a 开发者_C百科percentage. Are there any built in php functions for either action? I was thinking of doing a strpos('/'/, $grade); to check if it was a fraction but is there a cleaner way? Additionally to break up the fraction and convert it to a decimal my initial thought was to explode the fraction grade on a / and do (array[1] * 100) / array[2].

Is there any better solution than the one i am thinking?


if(is_nan($grade)) {
     if(strpos('/',$grade) !== false) {
          $numbers = explode($grade,'/');
          $percent = (((int)$numbers[0] / (int)$numbers[1])*100).'%';
     } else {
          echo "Not a valid grade!";
     }
} else { 
     $percent = $grade.'%';
}

i believe that should work

dont have to deal with pesky regex either


A quick function which you can just pass the values to:

function normal($number)
{
    $parts = explode("/", $number);
    return count($parts) > 1 ? ($parts[0] * 100) / $parts[1] : $parts[0];
}


Array index starts at zero, not one.

$array = explode('/', $str, 2);
if (count($array) === 2) {
    $grade = sprintf('%.2f', 100 * $array[0] / $array[1]);
} else {
    $grade = $str;
}


I'd do it like such:

public function convertFractions($givenValue){
        if(strpos($givenValue, "/") !== false){
            $strings = explode("/", $givenValue);
            return 100 * ($strings[0] / $strings[1]);
        } else {
            return $givenValue;
        }
    }

My one caveat would be: I'm not sure if the backslash requires escaping, as I've done here, as I didn't have time to test completely. If not, remove the backslash, and you should get the required values from the function every time.


Oh, thats a nice one, you can do it "easy" via regex:

$lines = array(
    "10/20",
    "20/10",
    "90",
);

foreach($lines as $line){
    if(preg_match('#([\d]+)/([\d]+)#',$line,$matches)){
        print (($matches[1]*100)/$matches[2])."% ";
    }else{
        print $line."% ";
    }

}

returns 50% 200% 90%

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜