Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using .NET string formatting, how do I format a string to display blank (empty string) for zero (0)?

I am using a DataBinder.Eval expression in an ASP.NET Datagrid, but I think this question applies to String formatting in .NET in general. The customer has requested that if the value of a string is 0, it should not be displayed. I have the following hack to accomplish this:

<%# IIf(DataBinder.Eval(Container.DataItem, "MSDWhole").Trim = "0", "", 
    DataBinder.Eval(Container.DataItem, "MSDWhole", "{0:N0}"))  %>

I would like to change the {0:N0} formatting expression so that I can eliminate the IIf statement, but can't find anything that works.

like image 930
Randy Eppinger Avatar asked Feb 17 '10 16:02

Randy Eppinger


People also ask

What is the use of 0 in C#?

The “0” custom specifier is a zero placeholder. If the value to be formatted has a digit in the position where the zero appears in the format string, the the digit is copied to the resultant string.

What is format string syntax?

The string format() method formats the given string into a nicer output in Python. The syntax of the format() method is: template. format(p0, p1, ..., k0=v0, k1=v1, ...)


2 Answers

You need to use the section separator, like this:

<%# DataBinder.Eval(Container.DataItem, "MSDWhole", "{0:N0;; }").Trim() %>

Note that only the negative section can be empty, so I need to put a space in the 0 section. (Read the documentation)

like image 75
SLaks Avatar answered Nov 15 '22 09:11

SLaks


Given the accepted answer:

<%# DataBinder.Eval(Container.DataItem, "MSDWhole", "{0:N0;; }").Trim() %>

The a space is placed in the the 3rd position, however placing a # in the third position will eliminate the need to call Trim().

<%# DataBinder.Eval(Container.DataItem, "MSDWhole", "{0:N0;;#}") %>
like image 44
David Avatar answered Nov 15 '22 09:11

David