Parsing a DBNULL value into double

2019-03-02 05:45发布

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.

3条回答
趁早两清
2楼-- · 2019-03-02 06:02

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楼-- · 2019-03-02 06:03

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.

查看更多
Evening l夕情丶
4楼-- · 2019-03-02 06:11

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

查看更多
登录 后发表回答