string.Format() 空白零

发布于 2024-09-28 17:34:17 字数 281 浏览 1 评论 0原文

在我的应用程序中,可以使用 string.Format() 函数来格式化字符串。我想添加当结果为零时返回空白的可能性。

据我所知,可以使用以下代码来执行此操作: 0.toString("0;; ");,但正如我已经提到的,我需要使用 string.Format() 函数(因为它必须能够使用例如 {0:P} 格式来表示百分比。

有谁知道如何使用 {0:P} 来空白零值>string.Format() 函数?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

囚你心 2024-10-05 17:34:17

String.Format() 支持 ; 部分分隔符。

尝试例如 String.Format("{0:#%;;' '}", 0);

String.Format() supports the ; section separator.

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

半葬歌 2024-10-05 17:34:17

我的回答有点晚了,但你可能想尝试以下方法:

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

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

{0:#.##%;-#.##%;''}
半夏半凉 2024-10-05 17:34:17

为什么不使用 if else 语句来实现呢?

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

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

string result = String.Format(the value);
if(result=="0")
{
   result=" ";
}
标点 2024-10-05 17:34:17

或者,也许更优雅地作为 int 上的扩展方法:

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

然后

(1+1-2).ToNonZeroString()

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()
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文