原文手動實作 format_money()
<?php
function format_money(string $str): string {
if ($str === '' || $str === '.00') return $str === '' ? '' : '0.00';
// 確保有小數點且小數兩位
if (strpos($str, '.') === false) $str .= '.00';
else {
$decimals = substr(strrchr($str, '.'), 1);
if (strlen($decimals) === 1) $str .= '0';
elseif (strlen($decimals) > 2) $str = substr($str, 0, strrpos($str, '.') + 3);
}
// 前導零處理
if ($str[0] === '.') $str = '0' . $str;
return $str;
}
// 測試
echo format_money('1234.5'); // 1234.50
echo format_money('0.1'); // 0.10
echo format_money('.99'); // 0.99
echo format_money('100'); // 100.00
?>
現代標準做法
<?php
// 1. 固定兩位小數 (不加千分位)
echo number_format(1234.5, 2, '.', ''); // 1234.50
// 2. 加上千分位
echo number_format(1234567.89, 2, '.', ','); // 1,234,567.89
// 3. 國際化貨幣 (需 intl 擴充套件)
$fmt = new NumberFormatter('zh_TW', NumberFormatter::CURRENCY);
echo $fmt->formatCurrency(1234567.89, 'TWD'); // NT$1,234,568
?>
適用場景比較
| 需求 | 推薦函數 |
| 簡單補齊小數兩位 | sprintf('%.2f', $num) 或 number_format($num, 2, '.', '') |
| 顯示千分位 | number_format($num, 2, '.', ',') |
| 多國幣別、符號、格式 | NumberFormatter::formatCurrency() |
| 高精度財務計算 | bcmath 或 brick/math 套件 |