NumberFormatter 是 PHP intl 擴充套件提供的強大類別,支援依地區設定格式化數字、貨幣、百分比等,自動處理貨幣符號位置、千分位分隔符、小數位數等細節,是多語系專案處理金額顯示的標準工具。
<?php
$amount = '12345.67';
// 英國格式(英鎊符號在前,逗號分隔千分位,點號小數點)
$fmtUK = new NumberFormatter('en_GB', NumberFormatter::CURRENCY);
echo 'UK: ' . $fmtUK->formatCurrency($amount, 'EUR') . "\n";
// 輸出:UK: €12,345.67
// 德國格式(歐元符號在後,點號分隔千分位,逗號小數點)
$fmtDE = new NumberFormatter('de_DE', NumberFormatter::CURRENCY);
echo 'DE: ' . $fmtDE->formatCurrency($amount, 'EUR') . "\n";
// 輸出:DE: 12.345,67 €
?>
| 地區代碼 | 語言/地區 | 貨幣代碼範例 |
|---|---|---|
| zh_TW | 繁體中文(台灣) | TWD, USD |
| zh_CN | 簡體中文(中國) | CNY, USD |
| en_US | 英文(美國) | USD |
| ja_JP | 日文(日本) | JPY |
| ko_KR | 韓文(韓國) | KRW |
| fr_FR | 法文(法國) | EUR |
<?php
$fmt = new NumberFormatter('zh_TW', NumberFormatter::CURRENCY);
$value = $fmt->parseCurrency('NT$12,345.67', $currency);
echo "數值:$value, 貨幣:$currency\n";
// 輸出:數值:12345.67, 貨幣:TWD
?>
<?php
function formatCurrency(float $amount, string $currency = 'TWD', string $locale = 'zh_TW'): string {
if (!extension_loaded('intl')) {
// 降級處理:簡單格式化
return number_format($amount, 2, '.', ',') . ' ' . $currency;
}
try {
$fmt = new NumberFormatter($locale, NumberFormatter::CURRENCY);
return $fmt->formatCurrency($amount, $currency);
} catch (Exception $e) {
error_log("NumberFormatter error: " . $e->getMessage());
return number_format($amount, 2, '.', ',') . ' ' . $currency;
}
}
// 使用
echo formatCurrency(12345.67, 'TWD', 'zh_TW'); // NT$12,345.67
echo formatCurrency(12345.67, 'USD', 'en_US'); // $12,345.67
echo formatCurrency(12345.67, 'EUR', 'de_DE'); // 12.345,67 €
?>
apt-get install php-intl;Windows: 啟用 php_intl.dll。NumberFormatter 物件有開銷,高頻呼叫時應重用實例或快取。NumberFormatter::formatCurrency() 是 PHP 專案處理國際化貨幣顯示的標準解法,正確使用可避免手動拼接字串造成的格式錯誤,並自動適應各地區慣用格式。