【问题标题】:C# float.Parse StringC# float.Parse 字符串
【发布时间】:2015-02-27 14:19:31
【问题描述】:

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

0 -0.01 -0.002

0.000833333333333 -0.01 -0.002

如果我在尝试

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

我从每一行读取值的代码(可能有问题):

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等循环数组

标签: c# .net string substring type-conversion


【解决方案1】:

float.Parse(string) method 默认使用您当前的文化设置。看起来您的 CurrentCultureNumberDecimalSeparator property, 而不是 .

这就是您在 "0.54" 示例中得到 FormatException 的原因。

作为一种解决方案,您可以使用具有. 作为NumberDecimalSeparator 的文化,例如InvariantCulture 作为Parse 方法中的第二个参数,或者您可以使用.Clone() 您的CurrentCulture 并将其设置为@987654339 @属性到.

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

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

【讨论】:

    【解决方案2】:

    您的文化似乎使用comma 作为小数分隔符。尝试用InvariantCulture解析它

    var value = float.Parse(tempLine.Substring(begin, end), CultureInfo.InvariantCulture);
    

    除此之外,解析行的方式比应有的复杂。您可以只拆分行而不是尝试处理索引:

    foreach(var str in tempLine.Split())  
    {
        float value = float.Parse(str, CultureInfo.InvariantCulture);
    }
    

    【讨论】:

    • 啊,我本来打算建议拆分,但我认为更多的是 float[] 作为输出,因此不需要任何循环。 float[] temp = float.Parse(tempLine.Split() );
    • 对不起这个作品float[] temp = tempLine.Split().Select(x =&gt; float.Parse(x)).ToArray();
    猜你喜欢
    • 2017-11-04
    • 2020-08-23
    • 1970-01-01
    • 2013-10-25
    • 2012-10-09
    • 1970-01-01
    • 1970-01-01
    • 2012-11-04
    • 1970-01-01
    相关资源
    最近更新 更多