Bjorn Bjorn - 1 year ago 108
C# Question

Use double.Parse that if Null value, then value replace with 0

I'm trying to convert a string to a double. If it encounters null value the value should then be 0 (zero). However, it comes up with an error message:

"Operator '??' cannot be applied to operands of type 'double' and 'double'. It's sort of confusing because both numbers are double? How do I fix this?

double final = double.Parse(min.ToString()) ?? 0.0;

Answer Source

Maybe this, assuming min is a string:

double final = double.Parse(min ?? "0");

Or perhaps:

double final = (min == null) ? 0 : double.Parse(min);


Even better:

double final = Convert.ToDouble(min);

Per the documentation, that method will return

A double-precision floating-point number that is equivalent to the number in value, or 0 (zero) if value is null.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download