【问题标题】:How to display percentage with one decimal and manage culture with string.Format in C#?如何在 C# 中使用小数点显示百分比并使用 string.Format 管理文化?
【发布时间】:2015-05-21 13:57:57
【问题描述】:

我想显示一个百分比并管理文化。 像这样: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 %”。

我尝试使用#.#,它可以工作,但我想管理当前的文化(小数分隔符、百分比位置等)。

我怎样才能做到这一点?

谢谢!

【问题讨论】:

  • 您可以将CultureInfo 实例直接传递给String.Format(和whatever.ToString),因为它实现了正确的接口:无需提取NumberFormat

标签: c# .net format percentage string.format


【解决方案1】:

格式中的句点 (.) 实际上是一个替换字符:区域性的小数分隔符1。请参阅 MSDN 上的 here

所以这部分很简单。

但是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("#'.'##").

【讨论】:

    【解决方案2】:

    Standard Numeric Format Strings

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

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

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

    • 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 %

    【讨论】:

      【解决方案3】:

      好的,谢谢,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);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-08-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多