Can I format NULL values in string.Format?

前端 未结 5 1971
粉色の甜心
粉色の甜心 2021-01-01 08:55

I was wondering if there\'s a syntax for formatting NULL values in string.Format, such as what Excel uses

For example, using Excel I could specify a format value of

5条回答
  •  情书的邮戳
    2021-01-01 09:19

    You can define a custom formatter that returns "NULL" if the value is null and otherwise the default formatted string, e.g.:

    foreach (var value in new[] { 123456.78m, -123456.78m, 0m, (decimal?)null })
    {
        string result = string.Format(
            new NullFormat(), "${0:#,000.00;(#,000.00);ZERO}", value);
        Console.WriteLine(result);
    }
    

    Output:

    $123.456,78
    $(123.456,78)
    $ZERO
    $NULL
    

    Custom Formatter:

    public class NullFormat : IFormatProvider, ICustomFormatter
    {
        public object GetFormat(Type service)
        {
            if (service == typeof(ICustomFormatter))
            {
                return this;
            }
            else
            {
                return null;
            }
        }
    
        public string Format(string format, object arg, IFormatProvider provider)
        {
            if (arg == null)
            {
                return "NULL";
            }
            IFormattable formattable = arg as IFormattable;
            if (formattable != null)
            {
                return formattable.ToString(format, provider);
            }
            return arg.ToString();
        }
    }
    

提交回复
热议问题