Fractions in PHP and whole numbers

I have been searching for a good PHP class for fraction handling and found Math_Fraction in the PEAR database.
However, it was still lacking a possibility to display the whole numbers of a fraction and I had to rewrite the last function in the Fraction.php file.
Here it is:

function toString($whole=false)
    $n = $this->getNum();
    $d = $this->getDen();
    if (($whole == false) || ($n<$d)) {
        return "$n/$d";
    else {
        if ($n==$d || $d==1) {
            return floatval($n / $d);
        else {
            $w = floor($n/$d);
            $n = ($n-($d*$w));
            return "$w $n/$d";


I have also informed the maintainer about it, so he might update it some time.
Meanwhile I invite you to use this simple, yet effective solution.

This entry was posted in php, Web. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *