Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

InspiredPrynce's avatar

Floats vs Integers

I have a function that checks the grade of students...

 public static function get_grade($score)
    {
        if($score>= 70){
            return 'A';
        }
        else if($score>= 60 && $score<= 69){
            return "B";
        }
        else if($score>= 50 && $score<=59){
            return "C";
        }
        else if($score>= 45 && $score<= 49){
            return "D";
        }
        else if($score>= 40 && $score<= 44){
            return "E";
        }
        else if($score>= 0 && 39){
            return "F";
        }
        else{
            return 'F';
        }
    }

I have this score 49.98 and from the function, it' supposed to fall into this category...

 else if($score>= 45 && $score<= 49){
       return "D";
 } 

But it returns "F" which happens to be here...

else{
    return 'F';
}

Please what could be the issue and how do i resolve this?

0 likes
5 replies
martinbean's avatar
Level 80

@InspiredPrynce Your code is working as expected. 49.98 is greater than 49, so doesn’t qualify as a ‘D’ grade.

You have cases for a grade less than and equal to 49, and equal or greater than 50, but nothing for a number between 49 and 50, which is why 49.98 falls all the way through to your else case.

Instead, consider checking the score against an array of grade boundaries and return the grade if the value satisfies one. If not, return ‘F’ by default:

$boundaries = [
    'A' => 70,
    'B' => 60,
    'C' => 50,
    'D' => 45,
    'E' => 40,
];

foreach ($boundaries as $grade => $threshold) {
    if ($score >= $threshold) {
        return $grade;
    }
}

return 'F';
1 like
InspiredPrynce's avatar

@martinbean please how do i fix this? I opted to round the number up but the points are needed so how do i check for number in between a range...

Thanks

InspiredPrynce's avatar

@martinbean Thank you so much man! I appreciate the help! It worked like a charm...

You are a life-saver.. You should be in the first aid kit!

1 like

Please or to participate in this conversation.