bcmath_compat
Pure PHP polyfill for the bcmath arbitrary-precision math extension
Repository Health
Technical Analysis
bcmath_compat is a pure-PHP polyfill for PHP’s bcmath extension, implementing the full set of bc* arbitrary-precision arithmetic functions so code that relies on bcmath keeps working on hosts where the native extension is not installed. It covers everything from bcadd and bcmul to bcpow, bcpowmod, bccomp, and bcscale.
Built and maintained by the phpseclib team, it leans on phpseclib’s BigInteger engine under the hood to deliver correct, well-tested results across PHP 5.x through 8.x.
What You Get
- Drop-in implementations of the
bc*arbitrary-precision math functions - Support for addition, subtraction, multiplication, division, modulo, and power operations
- Scale control via
bcscaleand per-call scale arguments - Comparison, square root, and modular exponentiation (
bcpowmod) helpers - Compatibility spanning PHP 5.x through 8.x
Common Use Cases
- Running bcmath-dependent code on shared hosts without the native extension
- Financial or monetary calculations requiring exact decimal arithmetic
- Cryptographic and big-number math in libraries like phpseclib
- Writing portable packages that must not assume ext-bcmath is present
Under The Hood
Architecture - The entire public surface is a single BCMath class in src/BCMath.php plus a bootstrap that defines global bc* functions when the native extension is absent. Each function delegates to phpseclib’s BigInteger math engine, handling scale, sign, and rounding semantics to match ext-bcmath’s behavior.
Tech Stack - Pure PHP with phpseclib’s BigInteger as its arithmetic backbone; development uses PHPUnit for testing and PHP_CodeSniffer for style enforcement.
Code Quality - The repository ships a PHPUnit suite that exercises the functions against expected bcmath output, and the README documents the few edge cases (like extension_loaded('bcmath') and ini_set('bcmath.scale')) that a polyfill cannot fully emulate.
API Design - Because it mirrors the exact bc* function names and signatures, adopting it requires no code changes: install via Composer and existing bcmath calls resolve to the polyfill automatically on hosts lacking the extension.