NumberFormatInfo.PercentDecimalDigits 屬性決定百分比格式("P")的小數位數。預設為 2 位,本文示範如何動態調整顯示精度以符合不同報表需求。
public int PercentDecimalDigits { get; set; }
ToString("P")、String.Format("{0:P}") 等格式化輸出using System;
using System.Globalization;
using System.Windows.Forms;
public class PercentFormatDemo
{
public void DemoPercentDecimalDigits()
{
// 使用繁體中文文化特性
NumberFormatInfo nfi = new CultureInfo("zh-TW", false).NumberFormat;
double value = 0.9774; // 97.74%
string info = "";
// 保留 1 位小數
nfi.PercentDecimalDigits = 1;
info += $"保留一位小數:{value.ToString("P", nfi)}\n";
// 輸出:97.7%
// 保留 2 位小數(預設)
nfi.PercentDecimalDigits = 2;
info += $"保留二位小數:{value.ToString("P", nfi)}\n";
// 輸出:97.74%
// 保留 4 位小數
nfi.PercentDecimalDigits = 4;
info += $"保留四位小數:{value.ToString("P", nfi)}\n";
// 輸出:97.7400%
// 保留 6 位小數
nfi.PercentDecimalDigits = 6;
info += $"保留六位小數:{value.ToString("P", nfi)}\n";
// 輸出:97.740000%
MessageBox.Show(info, "百分比小數位數自訂效果");
}
}
PercentDecimalDigits 四捨五入PercentSymbol,預設 "%")PercentPositivePattern/PercentNegativePattern 決定符號位置NumberFormatInfo nfi = new CultureInfo("en-US", false).NumberFormat;
nfi.PercentDecimalDigits = 2; // 小數位數
nfi.PercentSymbol = "%"; // 百分號符號
nfi.PercentGroupSizes = new int[] { 3 }; // 整數部分分組
nfi.PercentGroupSeparator = ","; // 分組分隔符
nfi.PercentPositivePattern = 1; // 正數模式:n %(如 97.74 %)
nfi.PercentNegativePattern = 0; // 負數模式:-n %(如 -97.74 %)
double rate = 0.12345;
string formatted = rate.ToString("P", nfi);
// 輸出:12.35 %
| 文化特性 | PercentSymbol | PercentPositivePattern | 範例 (0.5) |
|---|---|---|---|
| en-US | % | 0 (n%) | 50.00% |
| zh-TW | % | 0 (n%) | 50.00% |
| fr-FR | % | 1 (n %) | 50,00 % |
| de-DE | % | 1 (n %) | 50,00 % |
| ar-SA | ٪ | 0 (n%) | 50.00٪ |
public string FormatPercent(double value, int decimals = 2)
{
var nfi = (NumberFormatInfo)CultureInfo.CurrentCulture.NumberFormat.Clone();
nfi.PercentDecimalDigits = Math.Clamp(decimals, 0, 10);
return value.ToString("P", nfi);
}
// 使用
string p1 = FormatPercent(0.12345, 1); // "12.3%"
string p2 = FormatPercent(0.12345, 4); // "12.3450%"
// 使用者可切換精度的儀表板元件
public class PercentDisplay
{
private NumberFormatInfo _nfi;
private int _decimals = 2;
public PercentDisplay()
{
_nfi = (NumberFormatInfo)CultureInfo.CurrentCulture.NumberFormat.Clone();
}
public int Decimals
{
get => _decimals;
set
{
_decimals = Math.Clamp(value, 0, 6);
_nfi.PercentDecimalDigits = _decimals;
}
}
public string Format(double value) => value.ToString("P", _nfi);
}
Clone() 後修改NumberFormatInfo 實例不修改文化特性,直接使用自訂格式:
double value = 0.9774;
Console.WriteLine(value.ToString("P1")); // 97.7% (1位小數)
Console.WriteLine(value.ToString("P2")); // 97.74% (2位小數)
Console.WriteLine(value.ToString("P4")); // 97.7400% (4位小數)
// 完全自訂
Console.WriteLine((value * 100).ToString("F2") + "%"); // 97.74%
Console.WriteLine(string.Format("{0:0.00}%", value * 100)); // 97.74%
PercentDecimalDigits 提供簡單直觀的百分比精度控制。結合 PercentSymbol、PercentGroupSizes、PercentPositivePattern 等屬性,可完整掌控百分比顯示格式。實務上建議根據使用者偏好或報表規範動態調整,並注意文化特性差異對國際化應用的影響。