开发者

string.Format() Blank Zero

开发者 https://www.devze.com 2023-01-21 16:51 出处:网络
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.

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 s开发者_如何学Gotring.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?


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:#.##%;-#.##%;''}


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

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


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()
0

精彩评论

暂无评论...
验证码 换一张
取 消