views:

54

answers:

3

In my application, there are possibilities to format a string using the string.Format() function. I want to add the possibility to return blank when the result is zero.

As far as I can see, it is possible to do this using the code: 0.toString("0;; ");, but as i already mentioned, I need to use the string.Format() function (since it must be able to use for example the {0:P} format for percentage.

Does anyone knows how to blank a zero value using the string.Format() function?

Thank you, Peter

+5  A: 

String.Format() supports the ; section separator.

Try e.g. String.Format("{0:#%;;' '}", 0);.

Frédéric Hamidi
Unfortunately you can't mix standard and custom format strings like this.
LukeH
@Frédéric Hamidi Thank you for your answer. But this will return N when the value is 1, and -N when the value is -1 :(
Peter van Kekem
@LukeH Does that mean that it is not possible to perform this?
Peter van Kekem
@Peter: Can I clarify the requirements? If the number is non-zero then you want to apply the `P` standard format, but if the number is zero you want a blank?
LukeH
@LukeH Yes indeed
Peter van Kekem
@LukeH, you're right, the whole expression must be either standard or custom. I updated my answer accordingly.
Frédéric Hamidi
@Peter, what do you want to print if the value is -1?
Frédéric Hamidi
@Frédéric Hamidi the normal outcome, so in this case -100%
Peter van Kekem
@Peter, then my edited answer should be what you want :)
Frédéric Hamidi
@Frédéric Hamidi @LukeH Thanks for the updated answer. But the user of the application can choose several formats. One of them is currency, which ends up in the format {0:C}. This format will show a culture-specific result ($ in US, € in EU). However, a custom format cannot be culture specific. That's why I prefer standard expressions...
Peter van Kekem
+1  A: 

why don't you do it with if else statement?

string result = String.Format(the value); if(result=="0") { result=" "; }

william
Because I do edit an existing application where a format can be filled in somewhere. Adding a new format is as easy as editing an xml configuration file. Adding an if else statement will do indeed, but ends up in editing the code on every place the format is used...
Peter van Kekem
At the end, I have to use this solution. Thanks everyone for your answers!
Peter van Kekem
A: 

write an extension method:

public static string IntToString(this int input)
{
   return (input == 0)?"":String.Format(input);
}
SaeedAlg
Thank you but I prefer to perform this using a format (see comment at william's answer above)
Peter van Kekem