2

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;
2
  • What's the type of min? Can you share a complete example? Commented Jul 16, 2016 at 0:00
  • 2
    The reason for the error is that the left side of ?? has to be a nullable type. double can never be null, so it doesn't make sense to use ?? with it. Commented Jul 16, 2016 at 0:02

2 Answers 2

10

Maybe this, assuming min is a string:

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

Or perhaps:

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

EDIT

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Wow, thanks Smarx! It works :) I'll mark this as answered as soon as stack overflow allows me to.
0

This error appears because the left side of ?? must be a Nullable type that can take null as a value.

in your code:

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

You are using ?? operator which called Null-coalescing operator and what this operator do is checking if double.Parse(min.ToString()) __evaluates to a value has the type of double (which is a value type)_ is null or not. if it wasn't null, then assign the value to final, otherwise assigned 0.0 to it.

Since double is a value type and a value type variables cannot be null unless they are Nullable, you will get an error, and that's why you are getting this error:

"Operator '??' cannot be applied to operands of type 'double' and 'double'."

To solve this, you can try this:

 double final = Convert.ToDouble(min);

which return zero if min was null.

PS: try to avoid using the Parse method, which throw System.FormatExceptoin when it fails to parse, use TryParse instead:

string min = "2.s"; // not a number
double finals;
bool successed =  double.TryParse(min, out finals); // true if successed, otherwise false.
Console.WriteLine(successed? $"Yes! finals =  {finals}": $"No :( finals =  {finals}");
// finals is 0 if the parse didn't work.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.