Parsing a DBNULL value into double

自闭症网瘾萝莉.ら 提交于 2019-12-02 05:41:02

Another alternative would be to check if the datarow is DBNull:

double d = datarow is DBNull ? 0 : double.Parse(Convert.ToString(datarow));

This way, you do not need to check for DBNull.Value

DBNull can't be cast or parsed to double (or int, decimal, etc), so you have to check if datarow is DBNull before trying to parse it. It should be a oneliner using the ternary operator:

doubleValue = datarow == DBNull.Value ? 0.0 : double.Parse(Convert.ToString(datarow));

I have a bunch of conversion utility methods for such scenarios, in the format similar to this.

// tries to convert a general object to double, if a defaultValue is provided, it will silently fall back to it, if not, it will throw exceptions
public static double ToDouble(object obj, double? defaultValue = null) {
  if (obj == null || obj == "" || obj == DBNull.Value) return 0.0;
  try {
    if (obj is string)
      return double.Parse((string)obj);
    return Convert.ToDouble(obj);
  } catch {
    if (defaultValue != null) return defaultValue.Value;
    throw;
  }
}

I use this kind of weak-to-strong type conversion utilities mostly when I work with ADO.NET stuff, or other weakly typed interfaces, like reading data from Excel for example.

In my real code I also allow to pass a CultureInfo for string conversion, and do some other stuff like normalizing decimal signs, etc. to achieve the best format tolerance.

The general catch clause could be improved of course by catching specific exception types like FormatException, but for my needs it works good.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!