NumberFormatInfo.CurrencyGroupSizes 屬性控制貨幣值小數點左側的數字分組大小。預設為三位一組(如 1,234,567),本文示範如何自訂分組規則以符合不同地區或業務需求。
public int[] CurrencyGroupSizes { get; set; }
new int[] { 3 }(三位一組,無限重複)using System;
using System.Globalization;
using System.Windows.Forms;
public class CurrencyFormatDemo
{
public void DemoCustomGroupSizes()
{
// 取得 en-US 文化特性的數值格式資訊
NumberFormatInfo nfi = new CultureInfo("en-US", false).NumberFormat;
long value = 123456789012345; // 123 兆 4567 億 8901 萬 2345
// 方案 1:{2, 3, 1} → 從右:1位、3位、2位、2位、2位...(最後一組重複)
int[] sizes1 = { 2, 3, 1 };
nfi.CurrencyGroupSizes = sizes1;
string formatted1 = value.ToString("C", nfi);
// 結果:$12,34,56,78,90,12,3,45
// 方案 2:{2, 3, 2} → 從右:2位、3位、2位、2位、2位...
int[] sizes2 = { 2, 3, 2 };
nfi.CurrencyGroupSizes = sizes2;
string formatted2 = value.ToString("C", nfi);
// 結果:$12,345,67,89,01,23,45
MessageBox.Show(
$"原始格式:{value.ToString("C")}\n" +
$"{string.Join(",", sizes1)} 格式:{formatted1}\n" +
$"{string.Join(",", sizes2)} 格式:{formatted2}",
"貨幣分組大小自訂示範");
}
}
以 {2, 3, 1} 為例,數值 123456789012345 分組過程:
原始:123456789012345
從右分組:
第1組(1位):5
第2組(3位):234
第3組(2位):01
第4組(2位,重複最後一組):89
第5組(2位):67
第6組(2位):45
第7組(2位):23
第8組(剩餘1位):1
結果:1,23,45,67,89,01,234,5
| 地區/系統 | 分組模式 | CurrencyGroupSizes | 範例 (123456789) |
|---|---|---|---|
| 國際標準/美國 | 3位一組 | {3} | 123,456,789 |
| 印度/南亞 | 首組3位,其後2位 | {3, 2} | 12,34,56,789 |
| 中國傳統 | 4位一組(萬進制) | {4} | 1,2345,6789 |
| 自訂範例 | 2,3,1 循環 | {2, 3, 1} | 12,345,6,78,90,12,3,45 |
NumberFormatInfo nfi = new CultureInfo("zh-TW", false).NumberFormat;
// 完整自訂貨幣格式
nfi.CurrencySymbol = "NT$"; // 貨幣符號
nfi.CurrencyGroupSizes = new int[] { 3 }; // 分組大小
nfi.CurrencyGroupSeparator = ","; // 分組分隔符
nfi.CurrencyDecimalDigits = 2; // 小數位數
nfi.CurrencyDecimalSeparator = "."; // 小數點符號
nfi.CurrencyNegativePattern = 1; // 負數模式:-NT$123
decimal amount = -1234567.89m;
string result = amount.ToString("C", nfi);
// 輸出:-NT$1,234,567.89
CultureInfo.CurrentCulture.NumberFormat 為唯讀,需建立可寫入副本:(NumberFormatInfo)CultureInfo.CurrentCulture.NumberFormat.Clone()NumberFormatInfo 非執行緒安全,多執行緒環境建議各自建立實例CurrencyGroupSizes 提供強大的貨幣顯示自訂能力。理解其「從右至左、最後一組重複」的分組邏輯,配合 CurrencyGroupSeparator、CurrencySymbol 等屬性,即可實現符合各地區習慣的貨幣格式化輸出。實務上建議封裝為格式化工具類別,集中管理各文化特性的格式規則。