Fractions in PHP and whole numbers
April 20, 2010 – 18:52I 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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | 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.
