How to format a number as a string so that zero is replaced with an empty string

I need this to work in a single format statement and work for both ints and decimal places:

For example:

int myInt=0;
decimal myDecimal=0.0m;

// ... Some other code

string formattedResult1=String.Format("{0}",myInt);
string formattedResult2=String.Format("{0}",myDecimal);

      

Expected results:

"" (ie string.Empty) if the element to be formatted is zero and a numeric value (eg "123.456" for the decimal version) if it is not.

I need this to happen solely as a result of the format specification in the format string.

+3


source to share


2 answers


This should do:

string formattedResult1 = string.Format("{0:0.######;-0.######;\"\"}", myInt);

      



The colon introduces a numeric format string. The number format string is divided into 3 parts with semicolons: part 1 for positive numbers, part 2 for negative numbers, and part 3 for zeros. To define an empty string, you need to delimit it with double quotes, otherwise you won't like it.

See MSDN for full syntax .

+9


source


based on the accepted answer above, I did the same in Microsoft Report Builder

this worked for me (shows 2 decimal places, space for zero):



, ## +0.00; - #, ## 0.00; ""

+1


source







All Articles