Asp.net C语言中的自定义格式十进制和货币#

Asp.net C语言中的自定义格式十进制和货币#,asp.net,.net,visual-studio-2010,c#-4.0,Asp.net,.net,Visual Studio 2010,C# 4.0,我正在检索以下十进制值,需要将这些值转换为字符串 //百分比列 第1列:获取值为0.08,并应在UI中显示为8.00% //货币列 第2列:获取值为1000应在UI中显示为$1000 第3列:将值获取为3000应在UI中显示为$3000 有可能这样做吗 String PercentageCustomFormat="{PercentageCustomFormat}"; string CurrencyCustomFormat="{CurrencyCustomFormat}";

我正在检索以下十进制值,需要将这些值转换为字符串

//百分比列

第1列:获取值为0.08,并应在UI中显示为8.00%

//货币列

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

第3列:将值获取为3000应在UI中显示为$3000

有可能这样做吗

     String PercentageCustomFormat="{PercentageCustomFormat}";
     string CurrencyCustomFormat="{CurrencyCustomFormat}";
PercentageCustomFormat/CurrencyCustomFormat应包含一个逻辑,即如果任何列返回Null,则应显示为“NA”

检索:

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

提前谢谢

是的。您需要创建自己的和
ICustomFormatter
实现,并将其传递给
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();
  }
}

你能不能不这样做:

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

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

msdn上的这个url应该会有帮助,我希望这样:String PercentageCustomFormat=“{0:p:“NA”}”//不确定这是否正确PercentageCustomFormat/CurrencyCustomFormat还应包含if条件逻辑(即条件运算符?:),即如果任何列返回Null,它应显示为“NA”。我如何实现这一点?您应将“NA”放在通过检查
null
,CustomFormatProvider的
Format
方法中的逻辑。格式字符串中冒号后面的内容就是传递给
format
参数的内容。试试看。