2009-06-24 70 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