Search code examples
phpdecimalfractions

Decimal to fraction won't work for negative numbers


I have this script that coverts decimals to fractions:

function toFraction($number){ 
    $numerator = 1; 
    $denominator = 0; 
    for(; $numerator < 1000; $numerator++){ 
        $temp = $numerator / $number; 
        if(ceil($temp) - $temp == 0){ 
            $denominator = $temp; 
            break; 
        } 
    } 
    return ($denominator > 0) ? $numerator . '/' . $denominator : false; 
}

However, after some testing, it seems like it does not work for negative decimals. Why is this? Also, what is the solution to allow it to work with negative decimals?


Solution

  • It probably doesn't work because of the way your logic is set up in your for loop. What I would do is do a check to see if the number is negative at the beginning of your function. If it is, I would set a flag to remind the function that it was originally negative, and then I would flip the sign of the incoming $number. Then, right before returning, I would check to see if my flag was set, and if it was, I would simply invert the return value.

    function toFraction($number){ 
        if ($number < 0) {
            $number *= -1;
            $isInverted = true;
        }
    
        $numerator = 1; 
        $denominator = 0; 
        for(; $numerator < 1000; $numerator++){ 
            $temp = $numerator / $number; 
            if(ceil($temp) - $temp == 0){ 
                $denominator = $temp; 
                break; 
            } 
        } 
    
        if ($isInverted)
            $numerator *= -1;
    
        return ($denominator > 0) ? $numerator . '/' . $denominator : false; 
    }