Paul
Paul

Reputation: 449

C# > Convert string to double when input=""

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

Upvotes: 1

Views: 4479

Answers (7)

ThatAintWorking
ThatAintWorking

Reputation: 1360

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

Upvotes: 0

Kon
Kon

Reputation: 27451

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.

Upvotes: 0

Fredrik Mörk
Fredrik Mörk

Reputation: 158389

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

Upvotes: 3

yan
yan

Reputation: 20992

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

Upvotes: 1

Daniel DiPaolo
Daniel DiPaolo

Reputation: 56418

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.

Upvotes: 1

dana
dana

Reputation: 18155

Microsoft recommends using the Tester-Doer pattern as follows:

string input = "";
double numberd;
if( Double.TryParse(input, out numberd) )
{
    // number parsed!
}

Upvotes: 5

Jeff
Jeff

Reputation: 1291

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

Upvotes: 0

Related Questions