PHPackages                             mathematicator-core/numbers - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. mathematicator-core/numbers

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

mathematicator-core/numbers
===========================

Safety operations with numbers.

v2.1.3(5y ago)25.4k[2 PRs](https://github.com/mathematicator-core/numbers/pulls)7MITPHPPHP &gt;=7.2

Since Jul 25Pushed 3y ago1 watchersCompare

[ Source](https://github.com/mathematicator-core/numbers)[ Packagist](https://packagist.org/packages/mathematicator-core/numbers)[ Docs](https://github.com/mathematicator-core/numbers)[ RSS](/packages/mathematicator-core-numbers/feed)WikiDiscussions master Synced today

READMEChangelog (10)Dependencies (7)Versions (17)Used By (7)

 Smart PHP Number Utilities
============================

[](#----smart-php-number-utilities)

 [ ![](https://avatars3.githubusercontent.com/u/44620375?s=100&v=4) ](https://mathematicator.com)

[![Integrity check](https://github.com/mathematicator-core/numbers/workflows/Integrity%20check/badge.svg)](https://github.com/mathematicator-core/numbers/actions?query=workflow%3A%22Integrity+check%22)[![codecov](https://camo.githubusercontent.com/fb6aa313f44ee8fc0ee0292c47bb16009fc7bfe1b26dfc966717cf833a0519b4/68747470733a2f2f636f6465636f762e696f2f67682f6d617468656d6174696361746f722d636f72652f6e756d626572732f6272616e63682f6d61737465722f67726170682f62616467652e737667)](https://codecov.io/gh/mathematicator-core/numbers)[![Latest Stable Version](https://camo.githubusercontent.com/d22918db541f850ee714e6e7aee815f6293812515c8cf4a08bc83a3184457348/68747470733a2f2f706f7365722e707567782e6f72672f6d617468656d6174696361746f722d636f72652f6e756d626572732f762f737461626c65)](https://packagist.org/packages/mathematicator-core/numbers)[![Latest Unstable Version](https://camo.githubusercontent.com/4ff46e399dbf8647811099b314958b40dd401cbdcb073691cc609c10d1b60641/68747470733a2f2f706f7365722e707567782e6f72672f6d617468656d6174696361746f722d636f72652f6e756d626572732f762f756e737461626c65)](https://packagist.org/packages/mathematicator-core/numbers)[![License: MIT](https://camo.githubusercontent.com/1a2e0606685ce00663bf829868f794fd3fc9c86f8d80cae324734129e0723a58/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f4c6963656e73652d4d49542d627269676874677265656e2e737667)](./LICENSE)[![PHPStan Enabled](https://camo.githubusercontent.com/9142f3d2ec7588a75127608ff41f595540402524559c6f50feb756df4b8cf6c5/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f5048505374616e2d656e61626c65642532304c382d627269676874677265656e2e7376673f7374796c653d666c6174)](https://phpstan.org/)

**A PHP library to safely store and represent numbers and its equivalents in PHP.**

Store lots of number types exactly (**integers, decimals, fractions**) and convert them to each other. Expressions can be outputted as a **human string** (e.g. `1/2`) or **LaTeX** (e.g. `\frac{1}{2}`).

It is highly recommended to make sure you have enabled [BCMath](https://www.php.net/manual/en/book.bc.php)or [GMP](https://www.php.net/manual/en/book.gmp.php) extension on your PHP server for much faster calculations.

Installation
------------

[](#installation)

```
composer require mathematicator-core/numbers
```

Features
--------

[](#features)

- **SmartNumber** - Unified safe storage for all number types with an arbitrary precision. It supports comparisons.
    - **Entity\\Number** Less magic universal arbitrary precision number storage with basic features.
- **Fractions:**
    - **Entity\\Fraction** - Storage for simple or compound fraction that can consist from numbers and other expressions.
    - **Entity\\FractionNumbersOnly** - Storage for simple or compound fraction that consists only from numbers and is directly computable.
- **LaTeX support:** ([What is LaTeX?](https://en.wikipedia.org/wiki/LaTeX))
    - **MathLatexBuilder** - Create valid LaTeX for mathematical expressions in simple way with a fluent interface.
    - **MathLatexToolkit** - Statical library for LaTeX expressions (includes constants, functions, operators etc.)
    - **MathLatexSnippet** - Storage for LaTeX syntax.
- **Human string support:**
    - **MathHumanStringBuilder** - same interface as MathLatexBuilder, but produces human strings
    - **MathHumanStringToolkit** - same interface as MathLatexToolkit, but produces human strings (e.g. `1/2*(3+1)`)
- **Set generators**
    - Primary numbers
    - Even numbers
    - Odd numbers
- **Converters:**
    - Array to fraction and back
    - Decimal to fraction
    - Fraction to human string
    - Fraction to LaTeX
    - Int to Roman and back
- **Calculation** - simple arithmetic operations ([brick/math](https://github.com/brick/math) decorator)

💡 **TIP:** You can use [mathematicator-core/tokenizer](https://github.com/mathematicator-core/tokenizer)for advance user input string **tokenization** or [mathematicator-core/calculator](https://github.com/mathematicator-core/calculator)for advance **calculations**.

Usage
-----

[](#usage)

```
use Brick\Math\RoundingMode;
use Mathematicator\Numbers\SmartNumber;

$smartNumber = SmartNumber::of('80.500');
echo $smartNumber->toBigDecimal(); // 80.500
echo $smartNumber->toFraction()->getNumerator(); // 161
echo $smartNumber->toFraction()->getDenominator(); // 2
echo Calculation::of($smartNumber)->multipliedBy(-4); // -322.000
echo Calculation::of($smartNumber)->multipliedBy(-4)->abs()->getResult()->toInt(); // 322
echo $smartNumber->toBigDecimal()->toScale(0, RoundingMode::HALF_UP); // 81

$smartNumber2 = SmartNumber::of('161/2');
echo $smartNumber2->toHumanString(); // 161/2
echo $smartNumber2->toHumanString()->plus(5)->equals('90.5'); // 161/2+10=90.5
echo $smartNumber2->toLatex(); // \frac{161}{2}
echo $smartNumber2->toBigDecimal();  // 80.5
```

Recommended libraries
---------------------

[](#recommended-libraries)

For safe operations with arbitrary length numbers we recommend to use:

- [brick/math](https://github.com/brick/math) - Arbitrary precision arithmetic library for PHP with a simple interface.
- [PHP BC Math extension](https://www.php.net/manual/en/ref.bc.php) - Native PHP extension for arbitrary precision computing.

### Working with money

[](#working-with-money)

Use one of these libraries if you work with money in your application.

- [brick/money](https://github.com/brick/money) - A money and currency library with an interface like brick/math.
- [moneyphp/money](https://github.com/moneyphp/money) - Widely adopted PHP implementation of Fowler's Money pattern.

Why float is not safe?
----------------------

[](#why-float-is-not-safe)

**Float stores your number as an approximation with limited precision.**

You should never trust float to the last digit. Do not use floats directly for checking equity if you rely on precision (not only monetary calculations).

**Example:**

```
$result = 0.1 + 0.2;
echo $result; // output: 0.3

echo ($result == 0.3) ? 'true' : 'false'; // output: false
```

[How is float stored in memory?](https://softwareengineering.stackexchange.com/a/215126/354697)

[See in PHP manual](https://www.php.net/manual/en/language.types.float.php)

[Read more about float on Wikipedia](https://en.wikipedia.org/wiki/Floating-point_arithmetic)

Mathematicator Framework tools structure
----------------------------------------

[](#mathematicator-framework-tools-structure)

The biggest advantage is that you can choose which layer best fits your needs and start build on the top of it, immediately, without the need to create everything by yourself. Our tools are tested for bugs and tuned for performance, so you can save a significant amount of your time, money, and effort.

Framework tend to be modular as much as possible, so you should be able to create an extension on each layer and its sublayers.

**Mathematicator framework layers** ordered from the most concrete one to the most abstract one:

    **[ Search ](https://github.com/mathematicator-core/search)**    Modular search engine layer that calls its sublayers and creates user interface.      **[ Vizualizator ](https://github.com/mathematicator-core/vizualizator)**    Elegant graphic visualizer that can render to SVG, PNG, JPG and Base64.
 Extensions:  **[ Mandelbrot set generator ](https://github.com/mathematicator-core/mandelbrot-set)**       **[ Calculator ](https://github.com/mathematicator-core/calculator)**    Modular advance calculations layer.
 Extensions:  **[ Integral Solver ](https://github.com/mathematicator-core/integral-solver), [ Statistics ](https://github.com/mathematicator-core/statistic)**       **[ Engine ](https://github.com/mathematicator-core/engine)**    Core logic layer that maintains basic controllers, DAOs, translator, common exceptions, routing etc.      **[ Tokenizer ](https://github.com/mathematicator-core/tokenizer)**    Tokenizer that can convert string (user input / LaTeX) to numbers and operators.      **[ Numbers ](https://github.com/mathematicator-core/numbers)**    Fast &amp; secure storage for numbers with arbitrary precision. It supports Human string and LaTeX output and basic conversions.  **Third-party packages:**

⚠️ Not guaranteed!

    **[ REST API ](https://github.com/cothema/math-php-api)**    Install the whole pack as a REST API service on your server (Docker ready) or access it via public cloud REST API.  Contribution
------------

[](#contribution)

> Please help to improve this documentation by sending a Pull request.

### Tests

[](#tests)

All new contributions should have its unit tests in `/tests` directory.

Before you send a PR, please, check all tests pass.

This package uses [Nette Tester](https://tester.nette.org/). You can run tests via command:

```
composer test
```

For benchmarking, we use [phpbench](https://github.com/phpbench/phpbench). You can run benchmarks this way:

```
composer global require phpbench/phpbench @dev # only the first time
phpbench run
```

Before PR, please run complete code check via command:

```
composer cs:install # only the first time
composer fix # otherwise pre-commit hook can fail
```

###  Health Score

34

—

LowBetter than 75% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity25

Limited adoption so far

Community19

Small or concentrated contributor base

Maturity62

Established project with proven stability

 Bus Factor2

2 contributors hold 50%+ of commits

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~36 days

Recently: every ~44 days

Total

13

Last Release

2093d ago

Major Versions

v1.0.6 → v2.0.02020-04-14

PHP version history (2 changes)v1.0.0PHP &gt;=7.1.0

v2.1.0PHP &gt;=7.2

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/3382204?v=4)[baraja](/maintainers/baraja)[@baraja](https://github.com/baraja)

---

Top Contributors

[![janbarasek](https://avatars.githubusercontent.com/u/4738758?v=4)](https://github.com/janbarasek "janbarasek (64 commits)")[![flokixdev](https://avatars.githubusercontent.com/u/2387790?v=4)](https://github.com/flokixdev "flokixdev (63 commits)")[![dependabot-preview[bot]](https://avatars.githubusercontent.com/in/2141?v=4)](https://github.com/dependabot-preview[bot] "dependabot-preview[bot] (3 commits)")[![dependabot[bot]](https://avatars.githubusercontent.com/in/29110?v=4)](https://github.com/dependabot[bot] "dependabot[bot] (1 commits)")

---

Tags

fractionmathnumber-theorynumbersprecisionphpmathnumbersmathematicator

###  Code Quality

Static AnalysisPHPStan

Type Coverage Yes

### Embed Badge

![Health badge](/badges/mathematicator-core-numbers/health.svg)

```
[![Health](https://phpackages.com/badges/mathematicator-core-numbers/health.svg)](https://phpackages.com/packages/mathematicator-core-numbers)
```

###  Alternatives

[helsingborg-stad/municipio

A bootstrap theme for creating municipality sites.

4028.5k10](/packages/helsingborg-stad-municipio)[ssch/typo3-rector

Instant fixes for your TYPO3 PHP code by using Rector.

2603.2M436](/packages/ssch-typo3-rector)[flow-php/etl

PHP ETL - Extract Transform Load - Abstraction

378604.0k104](/packages/flow-php-etl)[drupol/phpermutations

Generators and iterators, permutations and combinations.

83717.2k5](/packages/drupol-phpermutations)[mathematicator-core/tokenizer

Math Tokenizer

105.0k6](/packages/mathematicator-core-tokenizer)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
