如何在GridView中格式化数字字符串?

4

在C#中,我有一个数据库中的处理时间数字列,格式为"###"或"##"(例如:"813"或"67")

当我将其绑定到网格视图时,希望以"0.###"的格式显示它(例如:"0.813"或"0.067")

我尝试使用{0:0.000}和其他格式化方式,但都无法正常工作。有人能告诉我如何编写格式字符串吗?


一个老问题,但我很惊讶还没有人建议使用自定义“,”说明符,它可用作数字缩放说明符来实现您想要的效果。请参见下面的答案。 - Joe
7个回答

4

在显示它之前,你应该将它乘以0.001,这样你就可以使用正常的{0:0.000}格式字符串。

如果由于某种原因不可能这样做-你可以使用格式字符串{0:0\\.000},它不将“.”作为小数分隔符,而是将其视为文字。


2

为使格式字符串生效,您需要在该列上禁用HTML编码。

更多阅读


1

可以使用“,”自定义格式说明符来完成此操作,该说明符可用作数字缩放说明符:

数字缩放说明符:如果在显式或隐式小数点的左侧立即指定一个或多个逗号,则要格式化的数字将每个逗号除以1000。

在您的示例中,格式字符串{0:0,.000}可用于将813格式化为0.813

两个逗号将按1,000,000进行缩放,例如{0:0,,.0M}将1753456格式化为1.8M


1
很好的帖子,真的很有帮助。但最好这样做:
try
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        if (((DataRowView)(e.Row.DataItem))["Columnname"].ToString().Equals("Total", StringComparison.OrdinalIgnoreCase))
        {
            e.Row.Font.Bold = true;
            //-----or ant thing you want to do------
        }
    }
}
catch (Exception ex)
{

}

0

你的意思是?

GridView.DataSource = .... 

BoundField total = new BoundField();
total.DataField = "Total";
total.HeaderText = "Total Amount";
total.DataFormatString = "{0:C}";
donations.Columns.Add(total);

......

0
如果由于某种原因您无法在将其绑定到网格之前更改该值,则可以处理RowDataBound事件并在显示之前将数字除以1000。
// Handle the grid's RowDataBound event
MyGridView.RowDataBound += new GridViewRowEventHandler(MyGridView_RowDataBound);

// Set the value to x / 1000 in the RowDataBound event
protected void MyGridView_RowDataBound( object sender, GridViewRowEventArgs e )
{
    if( e.Row.RowType != DataControlRowType.DataRow )
      return;

    // Cast e.Row.DataItem to whatever type you're binding to
    BindingObject bindingObject = (BindingObject)e.Row.DataItem;

    // Set the text of the correct column.  Replace 0 with the position of the correct column
    e.Row.Cells[0].Text = bindingObject.ProcessingTime / 1000M;
}

你不应该除以1000吗? - Kev
是的,我想是这样。我猜我并不担心那个特定的部分。 - Greg

0

那你是不是在找这样的东西?

String.Format("{0:0.000}", test/1000);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接