【问题标题】:Custom Format decimal and currency in C#C# 中的自定义格式小数和货币
【发布时间】:2023-03-28 02:48:01
【问题描述】:

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

// 百分比列

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

// 货币列

Column2:获取值为 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); 

提前致谢

【问题讨论】:

标签: asp.net .net visual-studio-2010 c#-4.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();
  }
}

【讨论】:

  • 我期待这样的事情:String PercentageCustomFormat="{0:P:"NA"}"; //不确定这是否正确 PercentageCustomFormat/CurrencyCustomFormat 还应包含 if 条件逻辑(即条件运算符?:),如果任何列返回 Null,则应显示为“NA”。我该如何实现?
  • 您可以通过检查 null 将“NA”逻辑放入 CustomFormatProvider 的 Format 方法中。格式字符串中冒号后面的任何内容都会传递给format 参数。试试看。
【解决方案2】:

你能不能只做这样的事情:

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

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

【讨论】:

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