kamiyonanayo / math
PHP arbitrary precision mathematics Library
Installs: 5
Dependents: 0
Suggesters: 0
Security: 0
Stars: 0
Forks: 0
pkg:composer/kamiyonanayo/math
Requires
- php: ^7.2 || ^8.0
- ext-json: *
Requires (Dev)
This package is auto-updated.
Last update: 2025-10-18 17:46:59 UTC
README
A PHP library for arbitrary precision mathematics. Inspired by Brick\Math.
The differences from the Brick/Math library are as follows:
- It is possible to specify a negative scale for BigDecimal.
- Support for
NAN,INFand-INF. - Three error modes: Throw Exception,
return null, andreturn NaN.
Installation
This library is installable via Composer:
composer require kamiyonanayo/math
Requirements
This library requires PHP 7.2 or later and BCMath extension.
Overview
Instantiation
The class constructor is not public, so you need to use a factory method to obtain an instance.
All classes provide the valueOf() factory method, which accepts one of the following types.
Numericinstancesintnumbersfloatnumbersstringrepresentation of integers, decimals, scientific notation, and special values like"NAN","INF","+INF","-INF".
Example
BigDecimal::valueOf(123546);
BigDecimal::valueOf('654321');
BigDecimal::valueOf(1.2);
BigDecimal::valueOf('9.99');
BigDecimal::valueOf('21E+10');
BigDecimal::valueOf('-5.274e-4');
BigDecimal::valueOf('-INF');
BigDecimal::valueOf('NAN');
Arithmetics
$n1 = BigDecimal::valueOf('12345.671');
$n2 = BigDecimal::valueOf('11111.111');
$n3 = $n1->add($n2)->multiply(-1);
echo $n3; // -23456.782
Immutable
$n1 = BigDecimal::valueOf('12345.671');
$n1->add(2);
...
echo $n1; // 12345.671
Comparisions
$n1 = BigDecimal::valueOf('12345.671');
$n2 = BigDecimal::valueOf('11111.111');
$n1->gt($n2); // true
$n1->eq(0); // false
$n2->lte(100); // false
Rounding
BigDecimal::valueOf(1)->divide('8', 2, RoundingMode::HALF_DOWN); // 0.12
BigDecimal::valueOf(1)->divide('8', 2, RoundingMode::HALF_UP); // 0.13
Error Mode
// NAN Return Mode (defautl)
BigDecimal::getContext()->setErrorMode(MathContext::ERROR_MODE_RETURN_NAN);
$n1 = BigDecimal::valueOf('12345');
$n1->add("ABC"); // NAN Object
// Null Return Mode
BigDecimal::getContext()->setErrorMode(MathContext::ERROR_MODE_RETURN_NULL);
$n1 = BigDecimal::valueOf('12345');
$n1->add("ABC"); // null
// throw Exception Mode
BigDecimal::getContext()->setErrorMode(MathContext::ERROR_MODE_THROW_EXCEPTION);
$n1 = BigDecimal::valueOf('12345');
$n1->add("ABC"); // NumberFormatException
TODO
- [ ] support BigDecimal#pow
- [ ] support BigDecimal#sqrt
- [ ] support BigDecimal#toEngineeringString​
- [ ] implementation BigInteger
- [ ] implementation BigRational