Reputation:
In C#
I have a processing time number data column in the database which is in in this format "###" or "##" ( eg: "813" or "67")
When I bind it to the grid view I wanted to display it in this format "0.###" (eg: "0.813" or "0.067")
I tried using {0:0.000} and other formatings. But none seem to work. Can anyone tell me how to write the format string?
Upvotes: 4
Views: 28487
Reputation: 124696
This can be done using the "," Custom Specifier, which can be used as a number scaling specifier:
Number scaling specifier: If one or more commas are specified immediately to the left of the explicit or implicit decimal point, the number to be formatted is divided by 1000 for each comma.
In your example, the format string {0:0,.000}
can be used to format 813 as 0.813
.
Two commas will scale by 1,000,000, e.g. {0:0,,.0M}
will format 1753456 as 1.8M
.
Upvotes: 1
Reputation: 11
Nice post, it really helped. But better to do it this way:
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)
{
}
Upvotes: 1
Reputation: 1402
So are you looking for something like this?
String.Format("{0:0.000}", test/1000);
Upvotes: 0
Reputation:
Do you mean?
GridView.DataSource = ....
BoundField total = new BoundField();
total.DataField = "Total";
total.HeaderText = "Total Amount";
total.DataFormatString = "{0:C}";
donations.Columns.Add(total);
......
Upvotes: 0
Reputation: 16680
If for some reason you can't change the value before you bind it to the grid, you can handle the RowDataBound event and divide the number by 1000 before displaying it.
// 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;
}
Upvotes: 0
Reputation: 85655
You should really multiply it by .001 before displaying it, then you can use the normal {0:0.000}
format string.
If, for some reason, that's not possible - you can use a format string of {0:0\\.000}
which uses the "." not as a decimal separator, but as a literal.
Upvotes: 4
Reputation: 16680
You need to disable HTML encoding on that column for the format string to take effect.
Upvotes: 2