Composer-installable fractions for PHP
use Phospr\Fraction;
echo new Fraction(1, 2); // 1/2
echo new Fraction(5, 2); // 2 1/2
echo Fraction::fromString('1 2/3'); // 1 2/3
echo Fraction::fromString('28/4'); // 7
echo Fraction::fromFloat(1.5); // 1 1/2
Fractions are simplified at construction
echo new Fraction(4, 6); // 2/3
$fraction = new Fraction(2, 7);
echo $fraction->add(new Fraction(3, 11)); // 43/77
$fraction = new Fraction(6);
echo $fraction->subtract(new Fraction(2, 3)); // 5 1/3
$fraction = new Fraction(1, 2);
echo $fraction->multiply(new Fraction(1, 2)); // 1/4
$fraction = new Fraction(6, 13);
echo $fraction->divide(new Fraction(2, 7)); // 1 8/13
$fraction = new Fraction(1, 8);
$fraction->toFloat(); // 0.125
Check whether a fraction is in fact a whole number.
$fraction = new Fraction(1, 8);
$fraction->isInteger(); // false
$fraction = new Fraction(16, 8);
$fraction->isInteger(); // true
Add package to your composer.json file
{
"require": {
"phospr/fraction": "dev-master"
}
}