Your problem is the last semicolon in the first input. The double.Parse
method is being passed an empty string. double value2 = double.Parse("");
There are several ways to fix this, I'll outline two here:
Check if the last character in the input is a semicolon, if so, strip it. (This should be self explanatory.)
Use the StringSplitOptions.RemoveEmptyEntries
overload.
I prefer the second option, myself. As this also removes issue with two consecutive semicolons.
string line = "4.1;4.0;4.0;3.8;4.0;;4.3;4.2;4.0;";
double[] values = line.Split(new char[]{';'}, StringSplitOptions.RemoveEmptyEntries).Select(double.Parse).ToArray();
Also, just to humour the idea that it could be a culture issue as well; the following code makes adjustments for culture-specific scenarios. The reason for the if
check is to save on compute time. It could be removed if you desire, with no harm to the overall affect. (It simply means that the programme will replace .
with .
in situations where the programme is run on a computer with a culture set to use decimals for separators. This is merely a simple optimization.)
string line = "4.1;4.0;4.0;3.8;4.0;;4.3;4.2;4.0;";
if (CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator != ".")
line = line.Replace(".", CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator);
double[] values = line.Split(new char[]{';'}, StringSplitOptions.RemoveEmptyEntries).Select(s => double.Parse(s)).ToArray();
Another sidebar about the potential for a culture issue: if it were a culture issue, the operation would not have thrown an exception, but instead simply return each digit of the number without separator. (I.e. 41, 40, 40, 38, 40, 43, 42, 40
)
Other options:
Use double.TryParse
instead.
Use a custom for
loop and manually parse your data.
There are likely other options as well that I cannot think of.
string line
but thenline2.Split...
. And the last;
is what does it. Remove the last semicolon and it works. – Abranchiatefor
loop anddouble.TryParse()
– Lindemanstring line
might bestring line2
in your first example? – Bluefield