문제

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

도움이 되었습니까?

해결책

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

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

다른 팁

String.Format() supports the ; section separator.

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

My answer is a bit late, but you may want to try the following:

{0:#.##%;-#.##%;''}

Or, perhaps more elegantly as an extension method on int:

public static class StringFormatters
{
    public static string ToNonZeroString(this int i) => i == 0 ? "" : i.ToString();
}

and then

(1+1-2).ToNonZeroString()
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top