[英]Wrong decimal places after parsing
我正在尝试从asc文件加载一些XY坐标。 它看起来像这样:
-55.988544 9382
-53.395804 9403
-50.804601 9433
然后我将坐标转换为浮点数。 但不知何故fe为第一个值我得到“-55988544.0”而不是“-55.988544” 。
这是代码:
private void btngettext_Click(object sender, EventArgs e)
{
StreamReader objStream = new StreamReader("C:\\...\\.asc");
firstLine = objStream.ReadLine();
int i = 0;
/*Split String on Tab,
* will separate words*/
string[] words = firstLine.Split('\t');
richTextBox1.Text = words[0];
foreach(string word in words)
{
if(word != "")
{
Console.WriteLine(word); //the value of the string is "-55.988544" here
//value = float.Parse(word); tried both
value = Convert.ToSingle(word); //here the float value is "-55988544.0"
Console.WriteLine(value.ToString());// "-5,598854E+07"
xyArray[0,i] = value;
i++;
}
}
}
此外,如果我使用objStream.ReadToEnd()或.Read(),如何迭代行。 读取第一行中的值,保存它们并继续下一行。
提前致谢,
BC ++
听起来你的应用程序是在“。”文化下运行的。 是千位分隔符而不是小数分隔符。 如果源文件总是使用“。”,那么最好用以下内容进行解析:
float.Parse(word, System.Globalization.CultureInfo.InvariantCulture);
这将确保解析使用“。”。 无论机器文化是什么。
这可能是文化设置的一个问题。 请尝试以下方法:
var culture = System.Globalization.CultureInfo.InvariantCulture;
value = float.Parse(word, culture);
如果您的数据使用已知的固定表示法来表示小数点分隔符等,则不应该依赖于读取PC的默认值。 采用
value = float.Parse(word, CultureInfo.InvariantCulture);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.