Reading a double value from a string

2019-02-26 08:56发布

问题:

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.

回答1:

Try to use

double d = Convert.ToDouble(h2, CultureInfo.InvariantCulture);

instead of

double d = Convert.ToDouble(h2);


回答2:

A number of people have already mentioned using Regex. If you are not very familiar with Regex, then this page might help you:

http://txt2re.com/index-csharp.php3?s=%22KL10124%20Traitor%20%232%20-%20%2bXX-%2b0.25%20-%20More%20Stuff%22&-7

Cheers



回答3:

d = double.Parse(h2,CultureInfo.InvariantCulture);

You need to set the format provider of the conversion operation to invariant.



回答4:

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);
}


回答5:

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.



回答6:

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.



回答7:

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.



回答8:

Use Regex

(?<=\+)([0-9\.])+


标签: c# .net double