萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 高精度浮點數運算:BCMath 擴展完全指南

為什麼需要 BCMath?

PHP 浮點數(IEEE 754 雙精度)存在精度缺失:

echo 0.1 + 0.2; // 0.30000000000000004
echo 134.7 - 52.5; // 82.19999999999999

金融、電商、科學計算**嚴禁**直接用浮點數運算。BCMath (Binary Calculator) 提供任意精度十進制運算,參數與返回值均為**字符串**,精度完全可控。

BCMath 核心函數速查

函數功能示例
bcadd($left, $right, $scale)加法bcadd('1.234', '5.678', 3) // '6.912'
bcsub($left, $right, $scale)減法bcsub('134.7', '52.5', 1) // '82.2'
bcmul($left, $right, $scale)乘法bcmul('0.1', '0.2', 2) // '0.02'
bcdiv($left, $right, $scale)除法bcdiv('10', '3', 4) // '3.3333'
bcmod($left, $right)取模bcmod('10', '3') // '1'
bcpow($base, $exp, $scale)冪bcpow('2', '10', 0) // '1024'
bcpowmod($base, $exp, $mod, $scale)冪取模(數論/加密常用)bcpowmod('2', '100', '1009', 0)
bcsqrt($num, $scale)平方根bcsqrt('2', 10) // '1.4142135623'
bccomp($left, $right, $scale)比較(-1/0/1)bccomp('1.000', '1', 3) // 0
bcscale($scale)設置全局默認小數位bcscale(4); bcadd('1', '1') // '2.0000'

實戰示例:金額計算鏈

// 設置全局精度 2 位(分)
bcscale(2);

$price    = '134.70';
$discount = '52.50';
$tax      = '82.20';

$afterDiscount = bcsub($price, $discount);     // '82.20'
$finalPrice    = bcsub($afterDiscount, $tax);  // '0.00'

echo "最終價格: $finalPrice"; // 0.00

進階:封裝為計算器類

class Decimal {
    private string $value;
    private int $scale;

    public function __construct(string $value, int $scale = 2) {
        $this->value = $value;
        $this->scale = $scale;
    }
    public function add(string $other): self {
        return new self(bcadd($this->value, $other, $this->scale), $this->scale);
    }
    public function sub(string $other): self {
        return new self(bcsub($this->value, $other, $this->scale), $this->scale);
    }
    public function mul(string $other): self {
        return new self(bcmul($this->value, $other, $this->scale), $this->scale);
    }
    public function div(string $other, int $scale = null): self {
        return new self(bcdiv($this->value, $other, $scale ?? $this->scale), $this->scale);
    }
    public function cmp(string $other): int {
        return bccomp($this->value, $other, $this->scale);
    }
    public function __toString(): string {
        return $this->value;
    }
}

// 使用
$total = new Decimal('100.00');
$total = $total->add('50.55')->sub('10.25')->mul('1.06'); // 含稅
echo $total; // 148.72

安裝與啟用

  • Linux:yum install php-bcmath / apt-get install php-bcmath / apk add php-bcmath
  • Windows:PHP 內建,取消 php.ini 中 ;extension=bcmath 註釋。
  • 驗證:php -m | grep bcmath 或 function_exists('bcadd')。

替代方案對比

方案精度性能適用場景
BCMath任意精度(字符串)中等(C 實現)金融、電商、精確計費
GMP (gmp_*)任意精度整數高(C 實現)大整數、加密、組合數學
浮點數 + round()~15 位有效數字極高(硬件)科學計算、圖形、非精確業務
brick/math (PHP 庫)任意精度、不可變對象中等(純 PHP)現代框架、領域模型、類型安全

總結

凡涉及金額、費率、匯率、庫存扣減等精確計算,必須使用 BCMath(或 GMP/brick/math)。 永遠不要用浮點數存儲/計算金錢。設置全局 bcscale 或封裝 Decimal 類型,將精度策略集中管理,杜絕「分不清是 0.01 還是 0.0099999」的生產事故。

copyright © 萬盛學電腦網 all rights reserved