[英]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.