PHP 浮點數運算存在精度缺失 (如 0.1 + 0.2 != 0.3),金融、電商、科學計算必須使用 BCMath 任意精度數學擴充。本文完整介紹 BCMath 核心函數、參數說明、實戰範例與最佳實踐。
<?php
echo 0.1 + 0.2; // 0.30000000000000004
echo 134.7 - 52.5 - 82.2; // 0.0000000000000142 (應為 0)
?>
IEEE 754 雙精度浮點數無法精確表示十進制小數,導致累積誤差。
| 函數 | 功能 | 參數 | 回傳 |
|---|---|---|---|
bcadd($left, $right, $scale?) | 加法 | 字串數字, 可選小數位 | 字串 |
bcsub($left, $right, $scale?) | 減法 | 同上 | 字串 |
bcmul($left, $right, $scale?) | 乘法 | 同上 | 字串 |
bcdiv($left, $right, $scale?) | 除法 | 同上 | 字串 |
bcmod($left, $right, $scale?) | 取模 | 同上 | 字串 |
bcpow($val, $exp, $scale?) | 冪次 | $exp 為非負整數 | 字串 |
bcpowmod($val, $exp, $mod, $scale?) | 模冪 (數論核心) | 大數加密常用 | 字串 |
bcsqrt($val, $scale?) | 平方根 | 字串 | |
bccomp($left, $right, $scale?) | 比較 | -1/0/1 (小於/等於/大於) | int |
bcscale($scale) | 設定預設小數位 | 全域影響 | void |
<?php
// 設定全域預設小數位 (分)
bcscale(2);
$price = '134.70';
$discount = '52.50';
$coupon = '82.20';
// 正確計算
$step1 = bcsub($price, $discount, 2); // 82.20
$final = bcsub($step1, $coupon, 2); // 0.00
echo "步驟1: $step1\n";
echo "最終: $final\n"; // 正確輸出 0.00
// 比較大小
if (bccomp($final, '0', 2) === 0) {
echo "金額歸零,可結單\n";
}
?>
<?php
class Decimal {
private string $value;
private int $scale;
public function __construct(string|float|int $value, int $scale = 2) {
$this->scale = $scale;
$this->value = (string)$value;
}
public function add(Decimal|string $other): self {
return new self(bcadd($this->value, (string)$other, $this->scale), $this->scale);
}
public function sub(Decimal|string $other): self {
return new self(bcsub($this->value, (string)$other, $this->scale), $this->scale);
}
public function mul(Decimal|string $other): self {
return new self(bcmul($this->value, (string)$other, $this->scale), $this->scale);
}
public function div(Decimal|string $other, int $scale = null): self {
return new self(bcdiv($this->value, (string)$other, $scale ?? $this->scale), $this->scale);
}
public function cmp(Decimal|string $other): int {
return bccomp($this->value, (string)$other, $this->scale);
}
public function __toString(): string {
return $this->value;
}
}
// 使用
$total = new Decimal('134.70');
$total = $total->sub('52.50')->sub('82.20');
echo $total; // 0.00
?>
number_format($float, 10, '.', '')bcdiv('1', '3', 2) → '0.33',需自行四捨五入'-123.45',正常運作| 方案 | 精度 | 效能 | 適用場景 |
|---|---|---|---|
| 原生 float | ~15 位有效數字 | 最快 (硬體) | 科學計算、圖形、非金融 |
| BCMath | 任意精度 | 中等 | 金融、電商、計費、加密 |
| GMP | 任意精度整數 | 快 | 大整數運算、密碼學 |
| PHP Decimal (擴充) | 任意精度 | 快 (C 實作) | 現代專案、物件導向 |
| brick/math (Composer) | 任意精度 | 純 PHP 但優化 | 無法安裝擴充環境 |
BCMath 是 PHP 解決浮點數精度問題的標準方案,掌握其字串介面特性、scale 機制、封裝模式,能構建可靠的金融級計算邏輯。