2009-06-24 73 views
8

有谁知道如何在.NET中构造格式字符串,以便生成的字符串包含冒号?通过在.NET中的格式字符串发出冒号

详细地说,我有一个值,比如200,我需要格式化为一个比例,即“1:200”。所以我构建了一个格式化字符串,如“1:{0:N0}”,它工作正常。问题是我想零显示为“0”,而不是“1:0”,所以我的格式字符串应该像“{0:1:N0 ;; N0}”,但当然这是行不通的。

任何想法?谢谢!

+0

感谢您的答复为止。我应该指出,我知道我可以按照建议做一些条件格式化,但实际上我需要一个格式字符串 - 例如应用于整列数据。 – user7239 2009-06-24 13:51:13

回答

15
using System; 

namespace ConsoleApplication67 
{ 
    class Program 
    { 
     static void Main() 
     { 
      WriteRatio(4); 
      WriteRatio(0); 
      WriteRatio(-200); 

      Console.ReadLine(); 
     } 

     private static void WriteRatio(int i) 
     { 
      Console.WriteLine(string.Format(@"{0:1\:0;-1\:0;\0}", i)); 
     } 
    } 
} 

1:4 
0 
-1:200 

;分离器在格式字符串中的意思是“做这样的正数;这样的负数;像这样零“。 \逃脱冒号。第三\不是严格必要的,因为一个文字零相同标准的数字格式输出零:)

1

如何:

String display = (yourValue == 0) ? "0" : String.Format("1:{0:N0}", yourValue); 
0

当然,一种办法是把它放在一个if语句,如果是零不同的格式化。

1
String.Format(n==0 ? "{0:NO}" : "1:{0:NO}",n); 
3

您可以使用AakashM的解决方案。如果你想要的东西稍微更具可读性,你可以创建自己的供应商:

internal class RatioFormatProvider : IFormatProvider, ICustomFormatter 
{ 
    public static readonly RatioFormatProvider Instance = new RatioFormatProvider(); 
    private RatioFormatProvider() 
    { 

    } 
    #region IFormatProvider Members 

    public object GetFormat(Type formatType) 
    { 
     if(formatType == typeof(ICustomFormatter)) 
     { 
      return this; 
     } 

     return null; 
    } 

    #endregion 

    #region ICustomFormatter Members 

    public string Format(string format, object arg, IFormatProvider formatProvider) 
    { 
     string result = arg.ToString(); 

     switch(format.ToUpperInvariant()) 
     { 
      case "RATIO": 
       return (result == "0") ? result : "1:" + result; 
      default: 
       return result; 
     } 
    } 

    #endregion 
} 

此服务供应商,您可以创建非常可读的格式字符串:

int ratio1 = 0; 
int ratio2 = 200; 
string result = String.Format(RatioFormatProvider.Instance, "The first value is: {0:ratio} and the second is {1:ratio}", ratio1, ratio2); 

如果你控制格式化类(而比像Int32这样的原始的),你可以使这看起来更好。有关更多详情,请参阅this article

+0

我现在没有编译器,所以我无法测试它,但我想你也可以将它写成扩展方法?像“String.FormatRatio(..)”? – 2009-06-24 14:10:27

+0

你当然可以这样做。 jemnery只是表示他想要一个格式字符串方法。 – 2009-06-24 14:14:14