phpmath / fraction
A PHP library to work with exact, immutable rational numbers.
Requires
- php: ^8.4
- ext-gmp: *
- phpmath/biginteger: ^3.0
Requires (Dev)
- phpmath/coding-standard: ^2.0
- phpstan/phpstan: ^2.3
- phpunit/phpunit: ^13.4
Suggests
None
Provides
None
Conflicts
None
Replaces
None
This package is auto-updated.
Last update: 2026-11-24 12:59:35 UTC
README
A PHP library to work with exact, immutable rational numbers. It is built on top of phpmath/biginteger, so numerators and denominators can be arbitrarily large.
Documentation
The full documentation is at https://phpmath.github.io/fraction/. Every change is listed in the changelog and every release on the releases page.
Install
composer require phpmath/fraction
Requirements
- PHP 8.4 or newer
- The
gmpextension phpmath/biginteger, which Composer installs for you
Usage
use PHPMath\Fraction\Fraction; $a = Fraction::of(1, 3); $b = Fraction::fromString('0.125'); // 1/8 echo $a->add($b); // 11/24 echo $a->toDecimalString(5); // 0.33333
Features
- Exact, immutable rational numbers, always stored in lowest terms
- Arbitrarily large numerators and denominators
- Arithmetic, comparison, powers and reciprocals
floor(),ceil(),round()andtruncate()- Exact decimal strings and a correctly rounded
toFloat()
Every exception implements FractionException, see the documentation for the full list.
Development
composer test
composer test-coverage
composer analyse
composer check-style
composer fix-style
Contributing
All contributions are welcome. Open an issue or a pull request on GitHub. Please follow the coding standard and add tests.
Security
If you discover a security issue, please create an issue in the issue tracker.
Credits
License
The MIT License (MIT). Please see License File for more information.