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 {0:#,000.00;-#,000.00,NULL}
, which means display the numeric value as number format if positive, number format in parenthesis if negative, or NULL if the value is null
string.Format("${0:#,000.00;(#,000.00);NULL}", someNumericValue);
Edit
I'm looking for formatting NULL
/Nothing
values for all data types, not just numeric ones.
My example is actually incorrect because I mistakenly thought Excel used the 3rd parameter if the value was NULL, but it's actually used when the value is 0. I'm leaving it in there because it's the closest thing I can think of to what I was hoping to do.
I am hoping to avoid the null coalescing operator because I am writing log records, and the data is not usually a string
It would be much easier to write something like
Log(string.Format("Value1 changes from {0:NULL} to {1:NULL}", new object[] { oldObject.SomeValue, newObject.SomeValue }));
than to write
var old = (oldObject.SomeValue == null ? "null" : oldObject.SomeValue.ToString()); var new = (newObject.SomeValue == null ? "null" : newObject.SomeValue.ToString()); Log(string.Format("Value1 changes from {0} to {1}", new object[] { old, new }));
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(); } }
I don't think there's anything in String.Format
that will let you specify a particular format for null
strings. A workaround is to use the null-coalescing operator, like this:
const string DefaultValue = "(null)"; string s = null; string formatted = String.Format("{0}", s ?? DefaultValue);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With