C#float.Parse字符串 [英] C# float.Parse String

查看:576
本文介绍了C#float.Parse字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是C#的新手,需要从文件中读取 float (x,y,z)
看起来像这样:

I'm new in C# and need to read float values (x, y, z) from file. It looks like:


0 -0.01 -0.002

0 -0.01 -0.002

0.000833333333333 -0.01 -0.002

0.000833333333333 -0.01 -0.002

如果Iam尝试

float number = float.Parse("0,54"); // it works well, but
float number = float.Parse("0.54"); // gains exepction.

我从每一行读取值的代码(可能会出错):

My code for reading values from each line (could be bugged):

int begin = 0;
int end = 0;
for (int i = 0; i < tempLine.Length; i++)
{
    if (Char.IsWhiteSpace(tempLine.ElementAt(i)))
    {
        end = i;
        float value = float.Parse(tempLine.Substring(begin, end));
        begin = end;
        System.Console.WriteLine(value);
    }
}

有人可以帮助吗?

推荐答案

float.Parse(string)方法默认使用当前的区域性设置。看起来像您的 CurrentCulture NumberDecimalSeparator 属性不是

这就是为什么您在 0.54 FormatException 的原因$ c>示例。

That's why you get FormatException in your "0.54" example.

作为解决方案,您可以使用具有的区域性。作为 NumberDecimalSeparator ,例如 InvariantCulture 作为 Parse 方法中的第二个参数,或者您可以 .Clone() 您的 CurrentCulture 并进行设置的 NumberDecimalSeparator 属性设置为

As a solution, you can use a culture have . as a NumberDecimalSeparator like InvariantCulture as a second parameter in Parse method, or you can .Clone() your CurrentCulture and set it's NumberDecimalSeparator property to .

float number = float.Parse("0.54", CultureInfo.InvariantCulture);

var culture = (CultureInfo)CultureInfo.CurrentCulture.Clone();
culture.NumberFormat.NumberDecimalSeparator = ".";
float number = float.Parse("0.54", culture);

这篇关于C#float.Parse字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆