函式名稱:NumberFormatter::formatCurrency()
適用版本:PHP 5 >= 5.3.0, PHP 7, PHP 8
函式說明: NumberFormatter::formatCurrency()函式用於將一個數字格式化為貨幣字串。它使用NumberFormatter物件來指定貨幣格式。
語法: string NumberFormatter::formatCurrency ( mixed $value , string $currency )
引數:
- value:需要格式化為貨幣的數字。可以是整數、浮點數或字串。
- currency:指定要使用的貨幣程式碼。例如,"USD"代表美元,"EUR"代表歐元等。可以參考ISO 4217標準。
返回值: 返回一個格式化後的貨幣字串。
示例:
$formatter = new NumberFormatter('en_US', NumberFormatter::CURRENCY);
$amount = 1234.56;
$currency = 'USD';
$result = $formatter->formatCurrency($amount, $currency);
echo $result; // 輸出: $1,234.56
$amount = 7890.12;
$currency = 'EUR';
$result = $formatter->formatCurrency($amount, $currency);
echo $result; // 輸出: €7,890.12
以上示例中,我們首先建立了一個NumberFormatter物件,指定了地區為"en_US"和貨幣格式。然後,我們使用formatCurrency()函式將數字格式化為貨幣字串。第一個示例中,將1234.56格式化為美元貨幣字串,結果是"$1,234.56"。第二個示例中,將7890.12格式化為歐元貨幣字串,結果是"€7,890.12"。
請注意,要使用NumberFormatter類,您需要確保PHP安裝了intl擴充套件。