[英]C# - Dealing with database type may be decimal or double
我正在使用以下代碼將數據從數據庫導入表中:
public double[,] toValueArray(string fieldPrefix, int firstIndex, int lastIndex)
{
// return a bunch of value columns as a double array
double[,] outArr = new double[TableRowCount,lastIndex-firstIndex+1];
for (int i = firstIndex; i <= lastIndex; i++)
{
var col = TheDataTable.Columns[fieldPrefix + i];
int r = -1;
foreach (DataRow row in TheDataTable.Rows)
{
outArr[++r, i - firstIndex] = (row[col] == null || row[col] == DBNull.Value) ? 0 : (double)row[col];
}
}
return outArr;
}
問題是,有時數據庫可能會將它們存儲為十進制,有時是雙精度。 僅當類型為小數時才如何轉換使用.toDouble()
?
首先,使用0D
獲得double值,並避免將int
隱式轉換為double
。 您可以嘗試使用Convert
類型的ToDouble
靜態方法進行Convert
。 樣品:
double setValue = 0D;
if (row[col] != null && row[col] != DBNull.Value)))
setValue = (row[col] is decimal) ? Convert.ToDouble(row[col]) : (double) row[col];
outArr[++r, i - firstIndex] = setValue;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.