Reading a double value from a string

2019-02-26 08:38发布

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.

标签: c# .net double
8条回答
Viruses.
2楼-- · 2019-02-26 09:09

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.

查看更多
做个烂人
3楼-- · 2019-02-26 09:11

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

查看更多
Root(大扎)
4楼-- · 2019-02-26 09:20

Try to use

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

instead of

double d = Convert.ToDouble(h2);
查看更多
地球回转人心会变
5楼-- · 2019-02-26 09:25

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.

查看更多
叼着烟拽天下
6楼-- · 2019-02-26 09:27

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楼-- · 2019-02-26 09:28
d = double.Parse(h2,CultureInfo.InvariantCulture);

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

查看更多
登录 后发表回答