Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse strings to double with comma and point

Tags:

c#

I am trying to write a function which basically converts an array of strings to an array of strings where all the doubles in the array are rounded to the number of decimalplaces i set. There can also be strings in the array which are no double values at all.

string[,] values = new string[1, 3];  values[0, 0] = "hello"; values[0, 1] = "0.123"; values[0, 2] = "0,123";  int decimalPlaces = 2;  double tmp; string format = "F" + decimalPlaces.ToString(); IFormatProvider provider = CultureInfo.InvariantCulture; for (int i = 0; i < values.GetLength(0); i++) {     for (int j = 0; j < values.GetLength(1); j++)     {         if (double.TryParse(values[i, j], out tmp))         {             values[i, j] = tmp.ToString(format, provider);         }     } }  Console.ReadLine(); 

The result has to be: "hello" , "0.12", "0.12" but it is "hello", "123.00", "0.12" will treat the comma in the wrong way. Does anyone have a simple and efficient solution for this?

like image 847
metacircle Avatar asked Jul 19 '12 12:07

metacircle


2 Answers

To treat both , and . as decimal point you must not only replace one with the other, but also make sure the Culture used parsing interprets it as a decimal point.

text = text.Replace(',', '.'); return double.TryParse(text, NumberStyles.Any, CultureInfo.InvariantCulture, out value); 
like image 112
hultqvist Avatar answered Sep 19 '22 15:09

hultqvist


You DO NOT NEED to replace the comma and dot..

I have had the very same problem. The reason is simple, the conversion culture plays a big role in which the comma or a dot is interpreted. I use a German culture where the comma distinguish the fractions, where as elsewhere the dot does the job.

Here I made a complete example to make the difference clear.

string[] doubleStrings = {"hello", "0.123", "0,123"}; double localCultreResult; foreach (var doubleString in doubleStrings) {     double.TryParse(doubleString, NumberStyles.Any, CultureInfo.CurrentCulture, out localCultreResult);     Console.WriteLine(string.Format("Local culture results for the parsing of {0} is {1}", doubleString, localCultreResult)); }  double invariantCultureResult; foreach (var doubleString in doubleStrings) {     double.TryParse(doubleString, NumberStyles.Any, CultureInfo.InvariantCulture, out invariantCultureResult);     Console.WriteLine(string.Format("Invariant culture results for the parsing of {0} is {1}", doubleString, invariantCultureResult)); } 

The results is the following: enter image description here

Play around with the culture and you will get the result you need.

like image 38
OliverAssad Avatar answered Sep 19 '22 15:09

OliverAssad