Showing number in 2 decimal places in GridView

gofor.net picture gofor.net · Oct 13, 2010 · Viewed 99.3k times · Source

I have one GridView in a .aspx page, and am showing dynamic data in this grid, setting AutoGenerateColumns="True".

Depending upon which of the options the user selects in a combo box, I am binding different DataTables to the GridView. For example, if the user selects Persons then I am fetching the Persons DataTable, and if the user selects Products then I am fetching Products DataTable.

How can I show a float or double number in 2 decimal places in GridView?

Answer

moribvndvs picture moribvndvs · Oct 15, 2010

The bound column should have a DataFormatString column. You could do something like:

DataFormatString="{0:0.00}" Numeric Custom Format Strings

UPDATE In the case of AutoGenerateColumns="true"... I'd have to know more specifics about what you're binding, but here are some avenues to explore:

  1. I'm not sure if GridView will respect the DataFormatAttribute in Data Annotations. If you are binding an object, and GridView respects that attribute, that might be one route to go.
  2. Wire the RowDataBound event and inspect each column for potential decimal values, and format that way.