echo intval(0.58 * 100); // 輸出 57,非預期的 58
這不是 PHP Bug,而是 IEEE 754 雙精度浮點數 在二進位無法精確表示十進位小數的普遍問題。
0.58 在二進位是無限循環小數:0.1001010001111010111000010100011110101110000101000111101...0.5799999999999999657.99999999999999,intval() 截斷為 57var_dump((0.1 + 0.7) == 0.8); // bool(false)
var_dump(floor((0.1 + 0.7) * 10)); // int(7) 非 8
「簡單的十進制分數如 0.1 或 0.7 不能在不丟失精度的情況下轉換為內部二進制格式……永遠不要相信浮點數結果精確到了最後一位,也永遠不要比較兩個浮點數是否相等。」
BCMath 函數以字串形式操作數字,支援任意精度,金融、電商、計價系統必用。
| 函數 | 功能 | 參數 | 回傳 |
|---|---|---|---|
bcadd($left, $right, $scale) | 加法 | 字串, 字串, 小數位數 | 字串 |
bcsub($left, $right, $scale) | 減法 | 同上 | 字串 |
bcmul($left, $right, $scale) | 乘法 | 同上 | 字串 |
bcdiv($left, $right, $scale) | 除法 | 同上 | 字串 |
bcmod($left, $right, $scale) | 取模 | 同上 | 字串 |
bcpow($base, $exp, $scale) | 冪次 | 字串, 字串, 小數位數 | 字串 |
bcsqrt($num, $scale) | 平方根 | 字串, 小數位數 | 字串 |
bccomp($left, $right, $scale) | 比較 | 字串, 字串, 小數位數 | -1/0/1 |
bcscale($scale) | 設定預設小數位 | 整數 | void |
// 設定全域預設小數位(選用)
bcscale(4);
$price = '199.99';
$qty = '3';
$taxRate = '0.05';
// 總價 = (單價 * 數量) * (1 + 稅率)
$subtotal = bcmul($price, $qty, 4); // 599.97
$tax = bcmul($subtotal, $taxRate, 4); // 29.9985
$total = bcadd($subtotal, $tax, 2); // 629.97 (保留 2 位)
// 比較
if (bccomp($total, '629.97', 2) === 0) {
echo "金額核對正確";
}
// 避免浮點數比較陷阱
$a = '0.1'; $b = '0.7';
var_dump(bcadd($a, $b, 2) === '0.8'); // bool(true)
class Money {
private string $amount; // 以「分」為單位儲存整數,或字串保留小數
private int $scale = 2;
public function __construct(string $amount, int $scale = 2) {
$this->amount = $amount;
$this->scale = $scale;
}
public function add(Money $other): self {
return new self(bcadd($this->amount, $other->amount, $this->scale), $this->scale);
}
public function multiply(float|string $factor): self {
return new self(bcmul($this->amount, (string)$factor, $this->scale), $this->scale);
}
public function compareTo(Money $other): int {
return bccomp($this->amount, $other->amount, $this->scale);
}
public function __toString(): string {
return $this->amount;
}
}
gmp_init() 等函數支援大整數運算,適合純整數場景(如以「分」計價)。DECIMAL(19,4),PHP 用 BCMath 或整數分。==、===、intval()、floor()、round() 做關鍵業務判斷。"199.99" 傳遞,避免 JSON 數值精度損失。浮點數精度問題跨語言通用,理解 IEEE 754 原理並善用 BCMath/整數分法,是 PHP 開發者處理金融計算的必備基本功。