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?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

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

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
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
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C#

From novice to tech pro — start learning today.