Parsing a DBNULL value into double

随声附和 提交于 2019-12-20 05:13:06

问题


I use the following line to convert the datarow value into double.

double.parse(Convert.ToString(datarow));

If the datarow is DBNULL, I am getting the following exception:

'double.Parse(Convert.ToString(data))' threw an exception of type 'System.FormatException'

How to handle this one without using tryparse.


回答1:


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




回答2:


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));



回答3:


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.



来源:https://stackoverflow.com/questions/37202141/parsing-a-dbnull-value-into-double

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