You canโ€™t double it. Variable string

I have a problem parsing a string in double. I have a line reading StreamWriter 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 brackets, add them together and display them in the text box. 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 the correct format, which I find rather strange, since the regular expression should delete everything except the numbers inside the brackets. I even checked this by writing a line in a text box without adding them together, and showed "100,9850,57" . So, really, I donโ€™t understand why it cannot convert a string to double.

Hope you can tell me what I'm doing wrong.

+4
source share
6 answers

Your variable "par" contains a line that looks like this: "(100.98)", so it does not parse.

+2
source

change your regex to (?<=\()(([^)]*))(?=\))

+1
source

You can try - based on InvariantCulture

  var culture = CultureInfo.InvariantCulture; double result = double.Parse(par , culture); 
0
source

You can force double.Parse to use a culture that uses , as a decimal separator, for example:

 CultureInfo culture = new CultureInfo("de-DE"); double d = double.Parse(par, culture); 

This is a good idea if you want your program to also work on computers with different regional settings.

0
source

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; } 
0
source

I earned by trying to catch:

 string par = Regex.Match(line, @"(?<=\()(([^)]*))(?=\))").Value; try { double par2 = double.Parse(par); res += par2; } catch { } 

Thank you all for your help.

0
source

Source: https://habr.com/ru/post/1434883/


All Articles