C#数据表十进制精度

我有这个代码来向datatable添加新列:

 DataColumn col = new DataColumn(“column”,typeof(decimal));      
 col.Caption =“专栏”;
 mytable.Columns.Add(COL);

如何为此列指定小数精度,以便值始终采用我希望的格式?

你不能。 但是,您可以使用String.Format函数从表中检索值时格式化值:

 String.Format("{0:0.##}", (Decimal) myTable.Rows[rowIndex].Columns[columnIndex]); 

我自己也有同样的问题,我通过在应用启动时加载整个架构来修复它,然后在需要时从架构中引用列信息。

我只有一个Visual Basic示例,但希望它很容易转换为C#

建立

 ' in whatever class you do your database communication: Private _database As SqlDatabase Private Shared _schema As DataTable Sub New() ' or however you handle the connection string / database creation Dim connectionString as String = GetConnectionString() _database = New SqlDatabase(connectionString) RetrieveSchema() End Sub Private Function RetrieveSchema() as DataTable If _schema Is Nothing Then Using connection As SqlConnection = _database.CreateConnection() connection.Open() _schema = connection.GetSchema("Columns") End Using End If return _schema End Function Public Function GetColumnInformation(tableName As String, columnName As String) as DataRow Dim firstMatchingRow as DataRow = ( From row In _schema.Rows _ Where ( row("TABLE_NAME") = tableName AndAlso row("COLUMN_NAME") = columnName) )).FirstOrDefault() Return firstMatchingRow End Function 

用法

 Dim columnInformation As DataRow = Dal.GetColumnInformation(tableName, columnName) ' find the precision Dim precision = columnInformation("NUMERIC_PRECISION") Dim scale = columnInformation("NUMERIC_SCALE") ' convert the decimal to the column's format ' eg: 2.345 with a scale of 2 would result in ' 2.35 value = Decimal.Round(value, scale)