number_format() 是 PHP 格式化數字最常用的函式,支援千分位分隔符、小數位數、自訂小數點與分隔符號。本文詳細說明語法、參數組合、貨幣格式化實例與注意事項。
number_format(float $num, int $decimals = 0, string $dec_point = '.', string $thousands_sep = ','): string
參數說明:
$num:要格式化的數字(字串會自動轉型)。$decimals:小數位數(預設 0,無小數點)。$dec_point:小數點字元(預設 .)。$thousands_sep:千分位分隔符(預設 ,,只取第一個字元)。重要: 此函式支援 1、2 或 4 個參數,不支援 3 個參數(若給 3 參數會拋出錯誤)。
echo number_format(1000000); // 1,000,000
echo number_format(1000000, 2); // 1,000,000.00
echo number_format(1000000, 2, ',', '.'); // 1.000.000,00(歐洲格式)
// 台幣/美金:千分位逗號、小數點
function fmt_twd($amount) {
return 'NT$' . number_format($amount, 2);
}
// 歐元/德式:千分位點號、小數逗號
function fmt_eur($amount) {
return '€' . number_format($amount, 2, ',', '.');
}
// 會計格式:負數用括號、固定兩位小數
function fmt_accounting($amount) {
$fmt = number_format(abs($amount), 2);
return $amount < 0 ? "($fmt)" : $fmt;
}
echo fmt_twd(1234567.89); // NT$1,234,567.89
echo fmt_eur(1234567.89); // €1.234.567,89
echo fmt_accounting(-500); // (500.00)
$a = number_format(1000, 2); // "1,000.00"
$b = $a + 500; // PHP 會嘗試轉型,結果可能為 1000.5(逗號被忽略)
// 正確做法:運算完成後再格式化
$c = number_format(1000 + 500, 2); // "1,500.00"
echo number_format(0.1 + 0.2, 2); // 0.30(正常)
echo number_format(0.1 + 0.7, 2); // 0.799999... → 0.80(四捨五入正常)
// 極端精度需求請用 bcmath 或 gmp 擴充套件
echo number_format(1000, 0, '.', 'abc'); // 1a000(只取 'a')
echo number_format(-1234.5, 2); // -1,234.50
echo number_format(0, 2); // 0.00
需支援多國幣別、貨幣符號、區域化格式時,建議使用 NumberFormatter:
$fmt = new NumberFormatter('zh_TW', NumberFormatter::CURRENCY);
echo $fmt->formatCurrency(1234567.89, 'TWD'); // NT$1,234,568
echo $fmt->formatCurrency(1234567.89, 'USD'); // US$1,234,567.89
| 需求 | 呼叫方式 | 輸出範例 |
|---|---|---|
| 預設千分位 | number_format(10000) | 10,000 |
| 兩位小數 | number_format(10000, 2) | 10,000.00 |
| 歐洲格式 | number_format(10000, 2, ',', '.') | 10.000,00 |
| 中式萬進位 | 需自行實作或用 NumberFormatter | 1,0000 |