C#数据表精度十进制

问题描述

| 我有以下代码将新列添加到数据表中: 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
\' e.g.: 2.345 with a scale of 2 would result in 
\'       2.35
value = Decimal.Round(value,scale)
    

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...