繁体   English   中英

如何在C#中以小数点显示百分比并使用string.Format管理区域性?

[英]How to display percentage with one decimal and manage culture with string.Format in C#?

我想展示一个百分比并管理文化。 像这样: https : //msdn.microsoft.com/fr-fr/library/system.globalization.numberformatinfo.percentnegativepattern%28v=vs.110%29.aspx

我这样做:

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.FractionalPart == 0)类的任何尝试注定了基础二进制表示形式。 例如,未精确表示0.1(10%),并且乘以100(对于百分比显示)后不可能恰好是10。因此,“无小数位”实际上需要“足够接近整数值”:

var hasFraction = Math.Abs(value*100.0 - Math.Round(value*100, 0)) < closeEnough;

然后根据结果构建格式字符串。


1点 如果您想要一个不受文化影响的时期,则需要用单引号将其引用,例如。 value.ToString("#'.'##")

标准数字格式字符串

“ P”或“ p”(百分比):

  • 结果:数字乘以100,并显示一个百分号。
  • 支持的对象:所有数字类型。
  • 精度说明符:所需的小数位数。
  • 默认精度说明符:由NumberFormatInfo.PercentDecimalDigits定义。

详细信息:百分比(“ P”)格式说明符。

  • 1(“ P”,美国)-> 100.00%
  • 1(“ P”,fr-FR)-> 100,00%
  • -0.39678(“ P1”,美国)-> -39.7%
  • -0.39678(“ P1”,fr-FR)-> -39,7%

NumberFormatInfo.PercentDecimalDigits包含以下示例:

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%

好的,谢谢,所以这不可能用string.Format()

您对此有何看法?

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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM