Reputation: 2615
I've tried to solve this for hours and absolutely don't understand what the compiler is doing here. I have strings that basically look like this:
"KL10124 Traitor #2 - +XX-+0.25 - More Stuff"
and need to read off the double '0.25' programmatically. Calling the string above s, the following two lines don't work:
string[] h = s.Split('-');
string h2 = h[2].Substring(1,h[2].Length - 2);
double d = Convert.ToDouble(h2);
The output if I display d is "25". I thought it might depend on the '.' resp ',' culture dependency, but if I insert
double d = Convert.ToDouble(h2.Replace('.',','));
it does not change a thing, the output is still "25".
But finally, if I do the brute force method as below I get the verbatim output "0,25" on the screen
double d;
string[] h = s.Split('-');
string h2 = h[2].Substring(1,h[2].Length - 2);
if (h2.Contains("."))
{
string[] h3 = h2.Split('.');
d = Convert.ToDouble(h3[0]) + Convert.ToDouble(h3[1])/100;
}
else
{
d = Convert.ToDouble(h2);
}
return d;
Why exactly do the first two versions not work? The last bit of code cannot be the correct way to do this.
Upvotes: 2
Views: 7940
Reputation: 1607
Try the Regex way :
string input = "KL10124 Traitor #2 - +XX-+0.25 - More Stuff";
Match match = Regex.Match(input, "^.*([0-9]+\\.[0-9]+).*$");
if (match.Success)
{
double value = Convert.ToDouble(match.Groups[1].Value, CultureInfo.InvariantCulture);
Console.Write(value);
}
Upvotes: 5
Reputation: 2880
A number of people have already mentioned using Regex. If you are not very familiar with Regex, then this page might help you:
Cheers
Upvotes: 3
Reputation: 100238
Use a RegEx query like this:
^KL\d+ Traitor #\d \- \+XX\-\+(\d+\.\d+) \- .+
A grouping (expression in brackets) will give your the result.
See the sandbox.
Upvotes: 1
Reputation: 2639
Print h2 in the first code example to see if you are doing the substring extraction correctly.
Also using a regular expression to extract the numer would more straigthforward.
Upvotes: 0
Reputation: 3675
You should look at h2 before you convert. It looks like it does not include the decimal point. Convert.ToDouble might require the leading 0 to know it's a fraction also, I am not certain.
In general this is a lot easier with a regex. See this answer.
Upvotes: 1
Reputation: 23626
Try to use
double d = Convert.ToDouble(h2, CultureInfo.InvariantCulture);
instead of
double d = Convert.ToDouble(h2);
Upvotes: 6
Reputation: 14919
d = double.Parse(h2,CultureInfo.InvariantCulture);
You need to set the format provider of the conversion operation to invariant.
Upvotes: 2