PHP 浮點數(IEEE 754 雙精度)存在精度缺失:
echo 0.1 + 0.2; // 0.30000000000000004
echo 134.7 - 52.5; // 82.19999999999999
金融、電商、科學計算**嚴禁**直接用浮點數運算。BCMath (Binary Calculator) 提供任意精度十進制運算,參數與返回值均為**字符串**,精度完全可控。
| 函數 | 功能 | 示例 |
|---|---|---|
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
yum install php-bcmath / apt-get install php-bcmath / apk add php-bcmathphp.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」的生產事故。