从字符串读取一个double值 [英] Reading a double value from a string
问题描述
我试图来解决这个几个小时,完全不明白编译器在这里做。我有串,基本上是这样的:
KL10124叛徒#2 - + XX-+ 0.25 - 更多的东西
和需要读出双'0.25'编程。调用上述S中的字符串,下面的两行不工作:
的String [] H = s.Split(' - ');
串H 2 = H [2] .Substring(1中,h [2] .Length - 2);
双D = Convert.ToDouble(H2);
如果我显示输出的结果是25。我想这可能取决于'。 RESP,依赖文化,但如果我插入
双D = Convert.ToDouble(h2.Replace('')'。');
它不会改变任何事情,输出仍然是25。
但最后,如果我做的蛮力方法如下我得到的屏幕上逐字输出0.25
双D;
字符串[] H = s.Split(' - ');
串H 2 = H [2] .Substring(1中,h [2] .Length - 2);
如果(h2.Contains(。))
{
字符串[] H3 = h2.Split('。');
D = Convert.ToDouble(H3 [0])+ Convert.ToDouble(H3 [1])/ 100;
}
其他
{
D = Convert.ToDouble(H2);
}
返回D组;
到底为什么做了前两个版本无法正常工作?的code中的最后一位不能做到这一点的正确方法。
尝试使用
双D = Convert.ToDouble(H2,CultureInfo.InvariantCulture);
而不是
双D = Convert.ToDouble(H2);
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.
Try to use
double d = Convert.ToDouble(h2, CultureInfo.InvariantCulture);
instead of
double d = Convert.ToDouble(h2);
这篇关于从字符串读取一个double值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!