Reputation: 115
I have a problem with parsing a string to a double. I have a StreamWriter
reading lines from a text file. The text file has the following lines:
17-09-2012: (100,98)
17-09-2012: (50,57)
Now, I want to use the values from inside the parantheses, add them together and display them in a textbox. So far I have the following:
int counter = 0;
double res = 0;
string line;
System.IO.StreamReader file = new System.IO.StreamReader("d:\\test.txt");
while ((line = file.ReadLine()) != null)
{
string par = Regex.Match(line, @"\(([^)]*)\)").Value;
double par2 = double.Parse(par);
res += par2;
counter++;
}
file.Close();
textBox1.Text = res.ToString();
However, apparently the input string is not in a correct format, which I find rather odd, since the regex should remove everything but the numbers inside the parantheses. I have even checked for this by writing the string to the textbox without first adding them together, and it showed "100,9850,57"
. So truly, I do not understand, why it cannot convert the string to a double.
I hope you can tell me, what I am doing wrong.
Upvotes: 4
Views: 2817
Reputation: 115
I made it work, by making a try, catch:
string par = Regex.Match(line, @"(?<=\()(([^)]*))(?=\))").Value;
try
{
double par2 = double.Parse(par);
res += par2;
}
catch
{
}
Thanks, everyone for your help.
Upvotes: 0
Reputation: 25844
You can force double.Parse to use a culture that uses ,
as a decimal separator, like this:
CultureInfo culture = new CultureInfo("de-DE");
double d = double.Parse(par, culture);
That's a good idea anyway, if you want your program to work also on computers with different regional settings.
Upvotes: 0
Reputation: 2510
Setting your regex to (?<=\()(([^)]*))(?=\))
and using this helper should solve your problems:
public static double ParseDouble(string input)
{
// unify string (no spaces, only . )
string output = input.Trim().Replace(" ", "").Replace(",", ".");
// split it on points
string[] split = output.Split('.');
if (split.Count() > 1)
{
// take all parts except last
output = String.Join("", split.Take(split.Count() - 1).ToArray());
// combine token parts with last part
output = String.Format("{0}.{1}", output, split.Last());
}
// parse double invariant
double d = Double.Parse(output, CultureInfo.InvariantCulture);
return d;
}
Upvotes: 0
Reputation: 28970
You can try with - based on InvariantCulture
var culture = CultureInfo.InvariantCulture;
double result = double.Parse(par , culture);
Upvotes: 0
Reputation: 5578
Your "par" variable is containing a string that looks like: "(100,98)" which is why it's failing to parse.
Upvotes: 2