Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I format a number as a string, so that zero is replaced by the empty string

Tags:

c#

c#-4.0

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

For example:

int myInt=0;
decimal myDecimal=0.0m;

// ... Some other code

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

The expected results are:

"" (i.e., string.Empty) if the item to be formatted is zero and a numeric value (e.g., "123.456" for the decimal version) if it isn't.

I need for this to occur exclusively as a result of the format specification in the format string.

like image 780
Michael Goldshteyn Avatar asked Sep 16 '25 03:09

Michael Goldshteyn


1 Answers

This should do:

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

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

See MSDN for the full syntax.

like image 107
Christian Hayter Avatar answered Sep 19 '25 08:09

Christian Hayter