C# 字符串浮动?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1844510/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C# string to float?
提问by Bramble
I have this bit of code here:
我这里有这么一段代码:
int i = 0;
StreamReader re = File.OpenText("TextFile1.txt");
string input = null;
while ((input = re.ReadLine()) != null)
{
string[] sites = input.Split(' ');
for (int j = 0; j < sites.Length; j++)
{
MyArray[i, j] = Convert.ToInt32(sites[j]);
}
i++;
}
for (int a = 0; a < 5; a++)
{
for (int j = 0; j < 5; j++)
{
Console.Write(MyArray[a, j] + " ");
}
Console.WriteLine();
}
My problem is this line of code
我的问题是这行代码
MyArray[i, j] = Convert.ToInt32(sites[j]);
Its getting converted to an int, how do I convert it to a float?
它被转换为一个整数,我如何将它转换为一个浮点数?
采纳答案by SoapBox
MyArray[i, j] = Convert.ToSingle(sites[j]);
回答by Matt
Try float.Parse(string) or Double.Parse(string)
尝试 float.Parse(string) 或 Double.Parse(string)
回答by o.k.w
Convert.ToSinglemethod or whole bunch of others.
Convert.ToSingle方法或其他一大堆方法。
EDIT:
Here's an related article: Double.TryParse or Double.Convert - what is faster and more safe?of interest in SO.
编辑:
这是一篇相关文章:Double.TryParse 或 Double.Convert - 什么更快更安全?对 SO 感兴趣。