Double.TryParse([string to convert], out result);
TryParse
function which accepts two arrangements the first one is the string you want to convert and the second is the output parameter with the result value but the method it self return true or false based on conversion if conversion completed successfully then return true if not it will return false
Double.Parse([string to convert]);
Parse
function don't return true or false based on conversion it will try to convert if success it will return the value converted if not it will throw exception so if you want to use Parse
function you have to place it in try
and catch
clause to avoid exceptions
UPDATE the problem you facing in the string format it self
Here is a method that most closely resembles the code you've provided
public static decimal Parse(string input)
{
return decimal.Parse(Regex.Replace(input, @"[^\d.]", ""));
}
Here is an option that will support negative numbers, and will stop if it finds a second period value, thus reducing the number of strings it returns that are not valid decimal values. It also has a few other modifications not seen in the OP to handle additional cases your current code doesn't.
public static decimal Parse(string input)
{
return decimal.Parse(Regex.Match(input, @"-?\d{1,3}(,\d{3})*(\.\d+)?").Value);
}