money_format()是一個使用當前locale(地區設置)來格式化數字為貨幣字符串的函數。它的語法如下:
string money_format ( string $format , float $number )
其中:
$format是格式控製字符串,類似於sprintf()中使用的格式;
$number是你要格式化的數字(金額)。
為了讓money_format()正確工作,你必須先設置本地化環境。可以使用setlocale()函數來設置。例如,設置為美國地區的本地化格式:
setlocale(LC_MONETARY, 'en_US.UTF-8');
注意,不同系統(特別是Windows 與Linux)對locale 的支持不同,你可能需要安裝相應的語言包。
以下是一個格式化金額的完整示例:
setlocale(LC_MONETARY, 'en_US.UTF-8');
$amount = 1234.56;
echo money_format('%.2n', $amount);
輸出結果可能是:
$1,234.56
其中:
'%.2n'表示使用小數點後保留兩位的貨幣格式;
n是locale 定義的貨幣格式類型;
.2指定了小數點後的位數。
如果你想根據用戶語言動態顯示不同格式的金額,可以結合setlocale()動態設置:
$amount = 9876.54;
setlocale(LC_MONETARY, 'de_DE.UTF-8');
echo "德國格式: " . money_format('%.2n', $amount) . "\n";
setlocale(LC_MONETARY, 'fr_FR.UTF-8');
echo "法國格式: " . money_format('%.2n', $amount) . "\n";
輸出:
德國格式: 9.876,54 €
法國格式: 9 876,54 €
這對於國際化網站(如https://m66.net/ecommerce/intl-support)非常實用。
如前所述, money_format()在PHP 8 中已被移除。如果你使用的是新版PHP,推薦使用NumberFormatter (來自intl擴展)代替:
$amount = 5678.90;
$fmt = new \NumberFormatter('en_US', \NumberFormatter::CURRENCY);
echo $fmt->formatCurrency($amount, 'USD');
輸出:
$5,678.90
使用NumberFormatter不僅兼容新版本,還提供更強的國際化支持,適合生產環境。