首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 綜合知識

PHP number_format() 千分位格式化完整教學:參數詳解、貨幣顯示與常見陷阱

     編輯:PHP 綜合知識

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)

常見陷阱與解決方案

1. 回傳字串非數值,不可直接運算

$a = number_format(1000, 2); // "1,000.00"
$b = $a + 500;               // PHP 會嘗試轉型,結果可能為 1000.5(逗號被忽略)
// 正確做法:運算完成後再格式化
$c = number_format(1000 + 500, 2); // "1,500.00"

2. 浮點數精度問題

echo number_format(0.1 + 0.2, 2); // 0.30(正常)
echo number_format(0.1 + 0.7, 2); // 0.799999... → 0.80(四捨五入正常)
// 極端精度需求請用 bcmath 或 gmp 擴充套件

3. 千分位分隔符只取第一個字元

echo number_format(1000, 0, '.', 'abc'); // 1a000(只取 'a')

4. 負數與零的處理

echo number_format(-1234.5, 2); // -1,234.50
echo number_format(0, 2);       // 0.00

進階:MoneyFormatter (PHP 8.0+ / intl 擴充套件)

需支援多國幣別、貨幣符號、區域化格式時,建議使用 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
中式萬進位需自行實作或用 NumberFormatter1,0000
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved