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?
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);
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:
Play around with the culture and you will get the result you need.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With