如何在C#中用一位小数显示百分比并用string.Format管理区域性?
我想显示百分比并管理区域性。 像这样: 我这样做:如何在C#中用一位小数显示百分比并用string.Format管理区域性?,c#,.net,format,percentage,string.format,C#,.net,Format,Percentage,String.format,我想显示百分比并管理区域性。 像这样: 我这样做: double percentage = 0.239; NumberFormatInfo nfi = CultureInfo.CurrentCulture.NumberFormat; string percentageValue = string.Format(nfi, "{0:P1}", percentage); 它可以工作(例如,结果可以是“%23,9”或“23,9%”) 但如果不需要,我不想显示小数 =>“100%”而不是“100,0%”
double percentage = 0.239;
NumberFormatInfo nfi = CultureInfo.CurrentCulture.NumberFormat;
string percentageValue = string.Format(nfi, "{0:P1}", percentage);
它可以工作(例如,结果可以是“%23,9”或“23,9%”)
但如果不需要,我不想显示小数
=>“100%”而不是“100,0%”
我尝试使用#.#,它很有效,但我想管理当前的区域性(十进制分隔符、百分比位置等)
我怎样才能做到这一点
谢谢 格式中的句点(
)实际上是一个替换字符:区域性的十进制分隔符1。请参阅MSDN上的
所以这部分很简单
但是,p
格式的小数位数基于适用区域设置中的详细信息,没有“百分比数字”的自定义格式
另外
但是如果不需要的话,我不想显示小数
对于浮点值来说是非常困难的。作为近似值,任何类似于if(value.fractilpart==0)
的尝试都会导致底层二进制表示的失败。例如,0.1(10%)未精确表示,乘以100(百分比显示)后不可能精确表示为10。因此,“无小数位数”实际上需要“足够接近整数值”:
var hasfract=Math.Abs(值*100.0-Math.Round(值*100,0))
然后根据结果生成格式字符串
1即,如果你想要一个独立于文化的句号,你需要用单引号引用它,例如
value.ToString(“#’.”##“)
“p”或“p”(百分比):
- 结果:数字乘以100并以百分比符号显示
- 支持:所有数字类型
- 精度说明符:所需的小数位数
- 默认精度说明符:由NumberFormatInfo.PercentDecimalDigits定义。
- 1(“P”,美国)-超过100.00%
- 1(“P”,fr)->100,00%
- -0.39678(“P1”,美国)-39.7%
- -0.39678(“P1”,fr)->-39,7%
NumberFormatInfo nfi = new CultureInfo( "en-US", false ).NumberFormat;
// Displays a negative value with the default number of decimal digits (2).
Double myInt = 0.1234;
Console.WriteLine( myInt.ToString( "P", nfi ) );
// Displays the same value with four decimal digits.
nfi.PercentDecimalDigits = 4;
Console.WriteLine( myInt.ToString( "P", nfi ) );
这将导致输出:
- 12.34%
- 12.3400%
bool hasDecimal = !percentage.Value.ToString("P1", CultureInfo.InvariantCulture).EndsWith(".0 %");
string percentageMask = hasDecimal ? "{0:P1}" : "{0:P0}";
string percentageValue = string.Format(CultureInfo.CurrentCulture, percentageMask, percentage);
您可以将
CultureInfo
实例直接传递到String.Format
(和whatever.ToString
),因为它实现了正确的接口:无需提取NumberFormat
。
bool hasDecimal = !percentage.Value.ToString("P1", CultureInfo.InvariantCulture).EndsWith(".0 %");
string percentageMask = hasDecimal ? "{0:P1}" : "{0:P0}";
string percentageValue = string.Format(CultureInfo.CurrentCulture, percentageMask, percentage);