1

I would like to convert a string to double (very basic question isn't it ?)

string input = "45.00000";
double numberd = Double.Parse(input, CultureInfo.InvariantCulture);

=> my code works and I am very happy.

However I may have the following

string input = "";
double numberd = Double.Parse(input, CultureInfo.InvariantCulture);

In this case my code does not work and I get a Exception error ;( I wonder how I can manage such situation. Ideally when I get this I would like to have my variable numberd equal to null.

Can anyone help me ? Thx

7 Answers 7

5

Microsoft recommends using the Tester-Doer pattern as follows:

string input = "";
double numberd;
if( Double.TryParse(input, out numberd) )
{
    // number parsed!
}
Sign up to request clarification or add additional context in comments.

Comments

3

Use a Double for parsing, but a Double? for storing the value, perhaps?

Double number;
string input = ""; // just for demo purpose, naturally ;o)
Double? nullableNumber = 
    Double.TryParse(input, NumberStyles.Any, CultureInfo.InvariantCulture, out number) 
    ? (Double?)number 
    : null;

// use nullableNumber

Comments

1

Primitive types like double cannot be null. You can have a nullable version with double? but, Double.Parse does not return a double? (just a plain double).

You could use Double.TryParse and check the return condition and set a double? to null accordingly if that would suit better.

Comments

1

Why not just catch the exception and set your variable?

double numberd;
try {
  numberd = Double.Parse(input, CultureInfo.InvariantCulture);
} catch (System.FormatException e)
  numberd = 0.0;
}

Alternatively, you can use Double.TryParse

Comments

0

Add an if statement comparing strings or surround with try/catch block.

Comments

0

Assuming you aren't worried about other invalid values besides empty strings, here's a simple one-liner:

Double? numberd = (input.Length == 0) ? null : (Double?)Double.Parse(input, CultureInfo.InvariantCulture);

mzabsky was on the right path, however his solution won't build and you shouldn't hard-code empty string - it's better to check the length of a string.

Comments

0

How about

Double? numberd = String.IsNullOrEmpty(str) ? null : Double.Parse(str)

In my application, I am parsing CSV files and I want these empty strings to be zero so I return 0.0 instead of null and it's all good.

5 more

2 Comments

You would have to guarantee that str is a number, since String.IsNullOrEmpty("word") returns false, causing Double.Parse(str) to fail. Double.TryParse would be a better choice since it returns a boolean whether it succeeded.
Good catch except you can't use Double.TryParse in the ternary

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.