使用 .NET 字符串格式化,如何格式化字符串以显示零 (0) 的空白(空字符串)?

发布于 2024-08-22 06:53:01 字数 347 浏览 5 评论 0原文

我在 ASP.NET Datagrid 中使用 DataBinder.Eval 表达式,但我认为这个问题通常适用于 .NET 中的字符串格式。客户要求如果字符串的值为0,则不应显示。我有以下技巧来实现此目的:

<%# IIf(DataBinder.Eval(Container.DataItem, "MSDWhole").Trim = "0", "", 
    DataBinder.Eval(Container.DataItem, "MSDWhole", "{0:N0}"))  %>

我想更改 {0:N0} 格式表达式,以便消除 IIf 语句,但找不到任何有效的内容。

I am using a DataBinder.Eval expression in an ASP.NET Datagrid, but I think this question applies to String formatting in .NET in general. The customer has requested that if the value of a string is 0, it should not be displayed. I have the following hack to accomplish this:

<%# IIf(DataBinder.Eval(Container.DataItem, "MSDWhole").Trim = "0", "", 
    DataBinder.Eval(Container.DataItem, "MSDWhole", "{0:N0}"))  %>

I would like to change the {0:N0} formatting expression so that I can eliminate the IIf statement, but can't find anything that works.

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

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

发布评论

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

评论(4

葬心 2024-08-29 06:53:01

您需要使用部分分隔符,如下所示:

<%# DataBinder.Eval(Container.DataItem, "MSDWhole", "{0:N0;; }").Trim() %>

请注意只有负数部分可以为空,因此我需要在 0 部分添加一个空格。 (阅读文档

You need to use the section separator, like this:

<%# DataBinder.Eval(Container.DataItem, "MSDWhole", "{0:N0;; }").Trim() %>

Note that only the negative section can be empty, so I need to put a space in the 0 section. (Read the documentation)

叶落知秋 2024-08-29 06:53:01

给出接受的答案:

<%# DataBinder.Eval(Container.DataItem, "MSDWhole", "{0:N0;; }").Trim() %>

空格放置在第三个位置,但是将 # 放置在第三个位置将消除调用 Trim() 的需要。

<%# DataBinder.Eval(Container.DataItem, "MSDWhole", "{0:N0;;#}") %>

Given the accepted answer:

<%# DataBinder.Eval(Container.DataItem, "MSDWhole", "{0:N0;; }").Trim() %>

The a space is placed in the the 3rd position, however placing a # in the third position will eliminate the need to call Trim().

<%# DataBinder.Eval(Container.DataItem, "MSDWhole", "{0:N0;;#}") %>
终陌 2024-08-29 06:53:01

使用自定义方法。

public static string MyFormat(double value) {       
    return value == 0 ? "" : value.ToString("0");
}

<%# MyFormat(Convert.ToDouble(Eval("MSDWhole"))) %>

Use a custom method.

public static string MyFormat(double value) {       
    return value == 0 ? "" : value.ToString("0");
}

<%# MyFormat(Convert.ToDouble(Eval("MSDWhole"))) %>
谈场末日恋爱 2024-08-29 06:53:01

尝试在像这样绑定的同时调用函数

<%# MyFunction( DataBinder.Eval(Container.DataItem, "MSDWhole") ) %>

,并在函数内部进行您想要的格式设置

Try to call a function while binding like this

<%# MyFunction( DataBinder.Eval(Container.DataItem, "MSDWhole") ) %>

and inside the function make the formatting you want

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