如何在 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 上的 here

所以那部分很简单。

但是 P 格式的小数位基于适用区域的详细信息,"percent digits" 没有自定义格式。

另外

But I don't want to display the decimal if not neede

对于浮点值来说非常困难。作为近似值,任何类似 if (value.FractionalPart == 0) 的尝试都注定了底层的二进制表示。例如 0.1 (10%) 没有准确表示,乘以 100(用于百分比显示)不太可能正好是 10。因此 "has no decimal places" 实际上需要 "sufficiently close to an integral value":

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

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


1 即。如果你想要一个独立于文化的时期,你需要引用它——用单引号——例如。 value.ToString("#'.'##").

Standard Numeric Format Strings

"P" or "p" (Percent):

  • Result: Number multiplied by 100 and displayed with a percent symbol.
  • Supported by: All numeric types.
  • Precision specifier: Desired number of decimal places.
  • Default precision specifier: Defined by NumberFormatInfo.PercentDecimalDigits.

More information: The Percent ("P") Format Specifier.

  • 1 ("P", en-US) -> 100.00 %
  • 1 ("P", fr-FR) -> 100,00 %
  • -0.39678 ("P1", en-US) -> -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);