PHPackages                             nanasess/bcmath-polyfill - 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. nanasess/bcmath-polyfill

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

nanasess/bcmath-polyfill
========================

PHP 8.4 bcmath functions polyfill with fallback compatibility for environments without bcmath extension. Based on phpseclib/bcmath\_compat with additional support for new PHP 8.4 bcmath functions.

1.0.3(2mo ago)086.6k↑30.5%[4 issues](https://github.com/nanasess/bcmath-polyfill/issues)[2 PRs](https://github.com/nanasess/bcmath-polyfill/pulls)MITPHPPHP &gt;=8.1

Since Jun 10Pushed 1w agoCompare

[ Source](https://github.com/nanasess/bcmath-polyfill)[ Packagist](https://packagist.org/packages/nanasess/bcmath-polyfill)[ RSS](/packages/nanasess-bcmath-polyfill/feed)WikiDiscussions main Synced 2d ago

READMEChangelog (5)Dependencies (10)Versions (48)Used By (0)

bcmath-polyfill
===============

[](#bcmath-polyfill)

 **PHP 8.4 bcmath functions polyfill with fallback compatibility for environments without bcmath extension.**

 [![Software License](https://camo.githubusercontent.com/55c0218c8f8009f06ad4ddae837ddd05301481fcf0dff8e0ed9dadda8780713e/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d627269676874677265656e2e7376673f7374796c653d666c61742d737175617265)](LICENSE.md) [![CI Status](https://github.com/nanasess/bcmath-polyfill/actions/workflows/ci.yml/badge.svg?branch=main&event=push)](https://github.com/nanasess/bcmath-polyfill/actions/workflows/ci.yml?query=branch%3Amain) [![PHPStan Level Max](https://camo.githubusercontent.com/cfad767368c5b88c30d3a7087a14099cb45895b5ded11e2ae54aa298b7ba5893/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f5048505374616e2d6c6576656c2532306d61782d627269676874677265656e2e7376673f7374796c653d666c61742d737175617265)](#) [![Latest Version](https://camo.githubusercontent.com/da15eb8f1933db1e559eddf1054be502951f606f37660e474843e41bff7edce8/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6e616e61736573732f62636d6174682d706f6c7966696c6c2e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/nanasess/bcmath-polyfill) [![Total Downloads](https://camo.githubusercontent.com/6a3faf14a6fee7266f64f9c00b75e090a551efd69e3d13d8c430c92ffb02f0e1/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f6e616e61736573732f62636d6174682d706f6c7966696c6c2e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/nanasess/bcmath-polyfill)

---

🚀 Features
----------

[](#-features)

- ✅ Complete bcmath extension polyfill for PHP 8.1+
- ✅ Supports all PHP 8.4+ bcmath functions including `bcfloor()`, `bcceil()`, and `bcround()`
- ✅ PHP 8.5 compatibility tested and verified
- ✅ Zero dependencies in production (uses phpseclib for arbitrary precision math)
- ✅ Seamless fallback when bcmath extension is not available
- ✅ 100% compatible with native bcmath functions

📦 Installation
--------------

[](#-installation)

Install via [Composer](https://getcomposer.org/):

```
composer require nanasess/bcmath-polyfill
```

🔧 Usage
-------

[](#-usage)

Simply include the polyfill in your project and use bcmath functions as you normally would:

```
// The polyfill will automatically load when bcmath extension is not available
require_once 'vendor/autoload.php';

// All bcmath functions work identically to the native extension
echo bcadd('1.234', '5.678', 2);    // 6.91
echo bcmul('2.5', '3.5', 1);        // 8.7
echo bcpow('2', '8');               // 256

// PHP 8.4 functions are also supported
echo bcfloor('4.7');                // 4
echo bcceil('4.3');                 // 5
echo bcround('3.14159', 2);         // 3.14

// bcround() supports RoundingMode enum (PHP 8.1+ with polyfill, native in PHP 8.4+)
echo bcround('2.5', 0, \RoundingMode::HalfAwayFromZero);  // 3
echo bcround('2.5', 0, \RoundingMode::HalfTowardsZero);   // 2
echo bcround('2.5', 0, \RoundingMode::HalfEven);          // 2
echo bcround('2.5', 0, \RoundingMode::HalfOdd);           // 3
```

📋 Supported Functions
---------------------

[](#-supported-functions)

### Classic bcmath Functions

[](#classic-bcmath-functions)

- `bcadd()` - Add two arbitrary precision numbers
- `bcsub()` - Subtract one arbitrary precision number from another
- `bcmul()` - Multiply two arbitrary precision numbers
- `bcdiv()` - Divide two arbitrary precision numbers
- `bcmod()` - Get modulus of an arbitrary precision number
- `bcpow()` - Raise an arbitrary precision number to another
- `bcsqrt()` - Get the square root of an arbitrary precision number
- `bcscale()` - Set/get default scale parameter
- `bccomp()` - Compare two arbitrary precision numbers
- `bcpowmod()` - Raise an arbitrary precision number to another, reduced by a specified modulus

### PHP 8.4 Functions (Added in [PR #6](https://github.com/nanasess/bcmath-polyfill/pull/6))

[](#php-84-functions-added-in-pr-6)

- `bcfloor()` - Round down to the nearest integer
- `bcceil()` - Round up to the nearest integer
- `bcround()` - Round to a specified precision with configurable rounding modes

#### RoundingMode Enum Support

[](#roundingmode-enum-support)

The `bcround()` function supports PHP 8.4's `RoundingMode` enum through a polyfill for PHP 8.1-8.3:

**Supported Modes:**

- `RoundingMode::HalfAwayFromZero` (equivalent to `PHP_ROUND_HALF_UP`)
- `RoundingMode::HalfTowardsZero` (equivalent to `PHP_ROUND_HALF_DOWN`)
- `RoundingMode::HalfEven` (equivalent to `PHP_ROUND_HALF_EVEN`)
- `RoundingMode::HalfOdd` (equivalent to `PHP_ROUND_HALF_ODD`)

**Not Yet Supported:**

- `RoundingMode::TowardsZero` - Throws `ValueError` (planned for future release)
- `RoundingMode::AwayFromZero` - Throws `ValueError` (planned for future release)
- `RoundingMode::NegativeInfinity` - Throws `ValueError` (planned for future release)

⚡ Performance
-------------

[](#-performance)

This polyfill uses [phpseclib](https://github.com/phpseclib/phpseclib)'s BigInteger class for arbitrary precision arithmetic, providing reliable performance for applications that cannot use the native bcmath extension.

### Performance Benchmarking

[](#performance-benchmarking)

This project includes a comprehensive benchmarking tool to compare the performance of the polyfill against native bcmath functions.

#### Local Benchmark Execution

[](#local-benchmark-execution)

```
# Run benchmark with default settings (10,000 iterations)
composer benchmark
# or
php benchmarks/run-benchmarks.php

# Export results in different formats
php benchmarks/run-benchmarks.php -f json -o results.json
php benchmarks/run-benchmarks.php -f csv -o results.csv
php benchmarks/run-benchmarks.php -f markdown -o BENCHMARK.md

# Show help
php benchmarks/run-benchmarks.php --help
```

#### Benchmark Configuration

[](#benchmark-configuration)

The benchmark tests include:

- **Basic Operations**: Addition, subtraction, multiplication, division with various number sizes
- **Advanced Operations**: Power, square root, modulo operations
- **Large Numbers**: Operations with 100, 500, and 1000 digit numbers
- **High Precision**: Operations with scale values of 20, 50, and 100

#### Interpreting Results

[](#interpreting-results)

Typical performance comparison shows:

- **Basic operations**: Polyfill is ~100-250x slower than native
- **Large numbers**: Performance gap increases with number size (up to ~800x slower)
- **Square root**: Interestingly, polyfill can be faster for high-precision operations

Example output:

```
BCMath Performance Benchmark
========================================
Iterations per test: 10000
Native BCMath: Available

Basic Operations
----------------
  Small numbers (10 digits):
    bcadd      | Native:    1.5ms | Polyfill:  230ms | Ratio: 150x slower
    ...

Summary
========================================
Average performance ratio: 26x
Polyfill is on average 26x slower than native

```

### GitHub Actions Integration

[](#github-actions-integration)

The project includes automated benchmarking workflows:

#### 1. PR Benchmarks (`/benchmark` command)

[](#1-pr-benchmarks-benchmark-command)

Comment `/benchmark` on any PR to run performance tests:

- Automatically triggered on PR updates to relevant files
- Quick mode (1,000 iterations) for fast feedback
- Results posted as PR comment

#### 2. Merge Benchmarks

[](#2-merge-benchmarks)

Automatically runs when PRs are merged to main:

- Full benchmark (10,000 iterations)
- Results posted to the merged PR for reference

#### 3. Manual Benchmarks

[](#3-manual-benchmarks)

Trigger via GitHub Actions UI:

- Customizable iteration count
- Multi-PHP version testing (8.1, 8.2, 8.3, 8.4, 8.5)
- Results saved as artifacts

### Performance Considerations

[](#performance-considerations)

While the polyfill is significantly slower than native bcmath:

- It provides full functionality when bcmath extension is unavailable
- Performance is adequate for most applications not requiring intensive calculations
- Consider using native bcmath for performance-critical applications

⚠️ Known Limitations
--------------------

[](#️-known-limitations)

### Extension Detection

[](#extension-detection)

- `extension_loaded('bcmath')` will return `false` when using the polyfill
- Recommended approach: Don't check for the extension, just use the functions

### Configuration Options

[](#configuration-options)

- **bcmath.scale INI setting is ignored**: When the native bcmath extension is not loaded, PHP does not recognize the `bcmath.scale` INI setting. This means:
    - `ini_get('bcmath.scale')` returns `false`
    - `ini_set('bcmath.scale', ...)` won't work
    - INI settings in php.ini or PHPT tests are ignored
    - The polyfill defaults to scale 0 when no explicit scale is provided
- **Workaround**: Use `bcscale()` instead to set the scale globally
- To get the current scale:
    - PHP &gt;= 7.3.0: Use `bcscale()` without arguments
    - PHP &lt; 7.3.0: Use `max(0, strlen(bcadd('0', '0')) - 2)`

### RoundingMode Enum Limitations

[](#roundingmode-enum-limitations)

- Three `RoundingMode` enum values are not yet implemented:
    - `RoundingMode::TowardsZero` - Will throw `ValueError`
    - `RoundingMode::AwayFromZero` - Will throw `ValueError`
    - `RoundingMode::NegativeInfinity` - Will throw `ValueError`
- These modes are planned for implementation in a future release
- Use traditional `PHP_ROUND_*` constants as alternatives when needed

🔄 Key Differences from phpseclib/bcmath\_compat
-----------------------------------------------

[](#-key-differences-from-phpseclibbcmath_compat)

Featurephpseclib/bcmath\_compatbcmath-polyfill**PHP 8.4 functions**❌ Not supported✅ Full support`bcfloor()`❌✅`bcceil()`❌✅`bcround()`❌✅**RoundingMode enum**❌ Not supported✅ Partial (4/7 modes)`HalfAwayFromZero`❌✅`HalfTowardsZero`❌✅`HalfEven`❌✅`HalfOdd`❌✅`TowardsZero`❌⏳ Planned`AwayFromZero`❌⏳ Planned`NegativeInfinity`❌⏳ Planned**PHP 8.2+ deprecations**⚠️ Warnings✅ Fixed**Test suite pollution**⚠️ Issues✅ Fixed**Active maintenance**❌ Limited✅ Active**CI/CD (PHP versions)**GitHub Actions (8.1, 8.2, 8.3)GitHub Actions (8.1, 8.2, 8.3, 8.4, 8.5)### Migration from phpseclib/bcmath\_compat

[](#migration-from-phpseclibbcmath_compat)

Switching is seamless - no code changes required:

```
# Remove old package
composer remove phpseclib/bcmath_compat

# Install bcmath-polyfill
composer require nanasess/bcmath-polyfill
```

🧪 Testing
---------

[](#-testing)

### Running PHPUnit Tests

[](#running-phpunit-tests)

```
# Install dependencies
composer install

# Run all tests
composer test
# or
vendor/bin/phpunit

# Run tests without bcmath extension
vendor/bin/phpunit --group without-bcmath
```

### Docker-based PHPT Testing

[](#docker-based-phpt-testing)

This project includes comprehensive Docker-based testing using official PHP core bcmath tests to ensure 100% compatibility:

```
# Build Docker test environment (PHP 8.3 by default)
docker build -f Dockerfile.test-without-bcmath -t bcmath-phpt-test .

# Run all PHPT tests
docker run --rm -v $PWD:/app bcmath-phpt-test

# Build and test with specific PHP version
docker build -f Dockerfile.test-without-bcmath --build-arg PHP_VERSION=8.4 -t bcmath-phpt-test:8.4 .
docker run --rm -v $PWD:/app bcmath-phpt-test:8.4

# Skip specific tests (supports exact test name matching)
docker run --rm -v $PWD:/app bcmath-phpt-test --skip bcceil,bcround,bcpowmod

# Run specific test file
docker run --rm -v $PWD:/app bcmath-phpt-test tests/php-src/bcadd.phpt

# Show help
docker run --rm bcmath-phpt-test --help
```

#### Available Options

[](#available-options)

- `--skip TESTS` - Comma-separated list of test names to skip (exact matching)
- `--help, -h` - Show usage information

#### Supported PHP Versions

[](#supported-php-versions)

- PHP 8.1, 8.2, 8.3, 8.4, 8.5

The Docker PHPT tests automatically run on GitHub Actions CI across all supported PHP versions to ensure comprehensive compatibility with the official PHP core bcmath test suite.

🤝 Contributing
--------------

[](#-contributing)

Contributions are welcome! Please feel free to submit a Pull Request.

📄 License
---------

[](#-license)

This project is licensed under the MIT License - see the [LICENSE.md](LICENSE.md) file for details.

🙏 Credits
---------

[](#-credits)

This project is a fork of [phpseclib/bcmath\_compat](https://github.com/phpseclib/bcmath_compat), originally created by the phpseclib team. We've extended it with PHP 8.4 function support and continue to maintain compatibility with all PHP versions.

---

 Made with ❤️ for the PHP community

###  Health Score

52

—

FairBetter than 96% of packages

Maintenance93

Actively maintained with recent releases

Popularity33

Limited adoption so far

Community11

Small or concentrated contributor base

Maturity58

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 69.6% of commits — single point of failure

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 ~69 days

Total

5

Last Release

72d ago

Major Versions

0.0.1 → 1.0.02025-09-05

### Community

Maintainers

![](https://www.gravatar.com/avatar/f2faa579847aa7f6045f80f897a15978403c8a3e0c1198f3d1ff72e32989309b?d=identicon)[nanasess](/maintainers/nanasess)

---

Top Contributors

[![nanasess](https://avatars.githubusercontent.com/u/815715?v=4)](https://github.com/nanasess "nanasess (249 commits)")[![terrafrost](https://avatars.githubusercontent.com/u/214474?v=4)](https://github.com/terrafrost "terrafrost (76 commits)")[![claude[bot]](https://avatars.githubusercontent.com/in/1236702?v=4)](https://github.com/claude[bot] "claude[bot] (15 commits)")[![dependabot[bot]](https://avatars.githubusercontent.com/in/29110?v=4)](https://github.com/dependabot[bot] "dependabot[bot] (13 commits)")[![actions-user](https://avatars.githubusercontent.com/u/65916846?v=4)](https://github.com/actions-user "actions-user (5 commits)")

---

Tags

polyfillBigIntegermathbigdecimalbcmath

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan, Rector

Code StylePHP CS Fixer

Type Coverage Yes

### Embed Badge

![Health badge](/badges/nanasess-bcmath-polyfill/health.svg)

```
[![Health](https://phpackages.com/badges/nanasess-bcmath-polyfill/health.svg)](https://phpackages.com/packages/nanasess-bcmath-polyfill)
```

###  Alternatives

[phpseclib/bcmath_compat

PHP 5.x-8.x polyfill for bcmath extension

16821.5M27](/packages/phpseclib-bcmath-compat)[brick/math

Arbitrary-precision arithmetic library

2.2k548.2M430](/packages/brick-math)[phpseclib/mcrypt_compat

PHP 5.x-8.x polyfill for mcrypt extension

28131.4M43](/packages/phpseclib-mcrypt-compat)[civicrm/civicrm-core

Open source constituent relationship management for non-profits, NGOs and advocacy organizations.

751291.4k43](/packages/civicrm-civicrm-core)[krowinski/bcmath-extended

Extends php BCMath lib for missing functions like floor, ceil, round, abs, min, max, rand for big numbers. Also wraps existing BCMath functions. (more http://php.net/manual/en/book.bc.php) Supports scientific notations

801.1M24](/packages/krowinski-bcmath-extended)[prestashop/decimal

Object-oriented wrapper/shim for BC Math PHP extension. Allows for arbitrary-precision math operations.

178.9M9](/packages/prestashop-decimal)

PHPackages © 2026

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