spacegrass/fraction

A composer-installable fractions library

1.0 2018-06-16 19:45 UTC

This package is auto-updated.

Last update: 2022-05-23 05:21:04 UTC


README

Composer-installable fractions for PHP

Usage

use Spacegrass\Fraction;

Simple Fractions

echo new Fraction(1, 2); // 1/2
echo new Fraction(5, 2); // 2 1/2

Create Fraction from string

echo Fraction::fromString('1 2/3'); // 1 2/3
echo Fraction::fromString('28/4'); // 7

Create Fraction from float

echo Fraction::fromFloat(1.5); // 1 1/2

Auto-simplified

Fractions are simplified at construction

echo new Fraction(4, 6); // 2/3

Addition

$fraction = new Fraction(2, 7);
echo $fraction->add(new Fraction(3, 11)); // 43/77

Subtraction

$fraction = new Fraction(6);
echo $fraction->subtract(new Fraction(2, 3)); // 5 1/3

Multiplication

$fraction = new Fraction(1, 2);
echo $fraction->multiply(new Fraction(1, 2)); // 1/4

Division

$fraction = new Fraction(6, 13);
echo $fraction->divide(new Fraction(2, 7)); // 1 8/13

To Float

$fraction = new Fraction(1, 8);
$fraction->toFloat(); // 0.125

Is Integer?

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

Installation

run composer require spacegrass/fraction

or

Add package to your composer.json file

{
    "require": {
        "spacegrass/fraction": "dev-master"
    }
}