Split and Convert string to double C#
Asked Answered
E

3

5

I want to convert string to double.

Here's example of what I do :

string line = "4.1;4.0;4.0;3.8;4.0;4.3;4.2;4.0;"; 

double[] values = line2.Split(';').Select(double.Parse).ToArray();

But an error appears

Input string was not in a correct format.

When I try

string line2 = "1;2;3;4;5;6;7;8;9;10;11;12";

double[] values = line2.Split(';').Select(double.Parse).ToArray();

It works perfectly fine.

What should be input format for double values to work ?

Evince answered 18/5, 2015 at 13:50 Comment(4)
Well the variables don't match. You do string line but then line2.Split.... And the last ; is what does it. Remove the last semicolon and it works.Abranchiate
Saver: use a for loop and double.TryParse()Lindeman
Also your string line might be string line2 in your first example?Bluefield
Thank you. I've been struggling for a whole day.Hereon
A
6

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:

  1. Check if the last character in the input is a semicolon, if so, strip it. (This should be self explanatory.)

  2. 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:

  1. Use double.TryParse instead.

  2. Use a custom for loop and manually parse your data.

There are likely other options as well that I cannot think of.

Abranchiate answered 18/5, 2015 at 13:58 Comment(10)
@Coder1409 This has everything to do with empty entries. I suggest you actually review and test the code he provided. And then test my code, and see the difference.Abranchiate
@RufusL This is correct; if you inspect the array that line.Split(';') creates on the input, you will notice that the last string produced is empty. ("") This is the exact issue for the OP.Abranchiate
@Coder1409 If he does, then that requires more information from the OP. If that is the issue, then the OP is encouraged to clear up his formatting. Until then, this completely fixed the issue for me.Abranchiate
@Coder1409 - Example that proves its the empty entry..Smoothspoken
I added decimal-separator detection.Abranchiate
Whether or not there are better safeguards to be used is irrelevant.Smoothspoken
@Smoothspoken It may be relevant, though not likely. At any rate, I have added culture-agnostic code as well, just to humour the idea for the OP.Abranchiate
@Coder1409 To be fair, the original issue is not at all a culture one, though I have added culture-agnostic code, so as to allow for rectification if this is the issue.Abranchiate
Also, @Coder1409, in case you were unaware, if it were a culture issue, the numbers would have been returned as whole numbers instead of decimal numbers, rather than throw an exception.Abranchiate
@Coder1409 Though that is the error he got, if you actually go test the code, you'll find that replacing the decimals with commas on a system that uses decimal separators will not throw that exception if you remove the empty entries. (I wouldn't expect you to know this; however, I don't think you ever plugged a line of code in.)Abranchiate
H
1

Another option would be to use the double.TryParse() method on each item in your split array. This will ensure that each item in the array (empty or not) is a valid double before attempting to add it to the values array.

For example:

string line = "4.1;4.0;4.0;3.8;4.0;4.3;4.2;4.0;";

double temp = 0;

double[] values = line.Split(';')
    .Where(item => double.TryParse(item, out temp))
    .Select(i => temp).ToArray();
Hamitosemitic answered 18/5, 2015 at 14:6 Comment(0)
B
1

It is due to your local clock settings. You can change on

Control Panel -> Clock and Region -> Region

change Formats to English(International)

double.Parse resolves numbers depending on local culture settings.

Beecham answered 4/4, 2024 at 13:2 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.