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 lik开发者_运维知识库e to have my variable numberd equal to null.
Can anyone help me ? Thx
Microsoft recommends using the Tester-Doer pattern as follows:
string input = "";
double numberd;
if( Double.TryParse(input, out numberd) )
{
// number parsed!
}
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
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.
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
Add an if statement comparing strings or surround with try/catch block.
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.
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
精彩评论