我有這樣的代碼來新列添加到數據表:C#的DataTable小數精度
DataColumn col = new DataColumn("column", typeof(decimal)); col.Caption = "Column"; mytable.Columns.Add(col);
如何指定此列小數精度所以價值總是會在我希望它是格式?
我有這樣的代碼來新列添加到數據表:C#的DataTable小數精度
DataColumn col = new DataColumn("column", typeof(decimal)); col.Caption = "Column"; mytable.Columns.Add(col);
如何指定此列小數精度所以價值總是會在我希望它是格式?
你不能。但是,您可以格式化值,當您使用String.Format
函數從表中檢索:
String.Format("{0:0.##}", (Decimal) myTable.Rows[rowIndex].Columns[columnIndex]);
好的。這意味着我有2個選項:1)要麼使用數據定義來限制小數數據類型的精度,我想在創建表時使用sql 2)使用Math.Round()或String.Format()進行顯示。 – Blablablaster 2011-05-30 13:17:12
@Blablablaster:你將如何使用數據定義來精確限制小數數據類型? – 2011-05-30 13:21:57
create table mytab(somefield decimal(18,2)) – Blablablaster 2011-05-30 13:43:09
我有同樣的問題我自己,我通過加載應用程序啓動時的整個架構,然後引用列固定它根據需要從架構獲取信息。
我只有一個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)
的格式應該由你的任何UI處理使用時,DataTable不應該關心格式化,只是數據。 – 2011-05-30 13:12:22