C#: Convert String to Double with Non Numerical Values Becoming 0

Using C#, how can I convert a string to a double in such a way as that if the string does NOT contain a double then 0 should be the value?
                    double xyz = Convert.ToDouble("0.123"); // Should be 0.123
                    double xyz = Convert.ToDouble("0"); // Should be 0
                    double xyz = Convert.ToDouble(""); // Should be 0
                    double xyz = Convert.ToDouble("hello world"); // Should be 0

Open in new window

LVL 10
skijAsked:
Who is Participating?
 
AndyAinscowFreelance programmer / ConsultantCommented:
Use TryParse instead.  If the TryParse fails then set the value to 0.
see:
https://msdn.microsoft.com/en-us/library/994c0zb1%28v=vs.110%29.aspx?cs-save-lang=1&cs-lang=csharp#code-snippet-1
where there is an example.
0
 
Fernando SotoRetiredCommented:
** NO POINTS **

Using TryParse as Andy stated, your code modified to show this
double xyz = 999;

Double.TryParse("0.123", out xyz); // Should be 0.123
Console.WriteLine(xyz);
xyz = 999;
Double.TryParse("0", out xyz); // Should be 0
Console.WriteLine(xyz);
xyz = 999;
Double.TryParse("", out xyz); // Should be 0
Console.WriteLine(xyz);
xyz = 999;
Double.TryParse("hello Wrold", out xyz); // Should be 0
Console.WriteLine(xyz);                   

Open in new window

0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.