C#中的自定义格式十进制和货币

时间:2013-09-26 11:53:09

标签: asp.net .net visual-studio-2010 c#-4.0

我正在检索小数值,需要将这些值转换为字符串。

//百分比列

column1:获取值为0.08,并在UI中显示为8.00%

//货币列

第2列:获取值1000应在UI中显示为$ 1000

column3:获取值为3000应在UI中显示为$ 3000

是否可以做这样的事情?

     String PercentageCustomFormat="{PercentageCustomFormat}";
     string CurrencyCustomFormat="{CurrencyCustomFormat}";

PercentageCustomFormat / CurrencyCustomFormat应该是一个逻辑,如果任何列返回Null,它应该显示为“NA”。

检索:

      String.Format("{PercentageCustomFormat}", column1);
      String.Format("{CurrencyCustomFormat}", column2); 

先谢谢

2 个答案:

答案 0 :(得分:1)

是。您需要创建自己的IFormatProviderICustomFormatter实施,并将其传递给string.Format。这将根据您传入的格式字符串处理您的自定义格式。

void Main()
{
    var formatter = new CustomFormatProvider();
    var formattedValue = string.Format(formatter, "A format {0:PercentageCustomFormat}", 8.0m);
}

class CustomFormatProvider : IFormatProvider, ICustomFormatter
{
   public object GetFormat(Type formatType)
   {
      return this;
   }   

  public string Format(string format, object arg, IFormatProvider formatProvider){
    if (format == "PercentageCustomFormat")
        return " ... your custom format ... ";

    return arg.ToString();
  }
}

答案 1 :(得分:0)

你能不能做这样的事情:

percentageString = column1 == null ? "N/A" : String.Format("{0:P0}", column1);
currencyString = column2 == null ? "N/A" : String.Format("{0:C0}", column2);

我不认为这里需要自定义格式提供程序。