C# float.Parse String
Asked Answered
M

3

22

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.000833333333333 -0.01 -0.002

If Iam trying

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);
    }
}

Someone could help?

Miranda answered 31/12, 2014 at 13:48 Comment(1)
I'd split the string by space and then loop the array with float.Parse etcSpectrometer
M
44

float.Parse(string) method uses your current culture settings by default. Looks like your CurrentCulture's NumberDecimalSeparator property is , not .

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

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);

or

var culture = (CultureInfo)CultureInfo.CurrentCulture.Clone();
culture.NumberFormat.NumberDecimalSeparator = ".";
float number = float.Parse("0.54", culture);
Meatiness answered 31/12, 2014 at 13:50 Comment(0)
B
8

It seems your culture uses comma as the decimal separator. Try parsing it with InvariantCulture:

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

In addition to this, the way you're parsing the lines is more complicated than it should be. You can just split the line instead of trying to deal with indices:

foreach(var str in tempLine.Split())  
{
    float value = float.Parse(str, CultureInfo.InvariantCulture);
}
Bienne answered 31/12, 2014 at 13:51 Comment(2)
Ah I was going to suggest the Split but was think more of a float[] as the output so no need for any loops. float[] temp = float.Parse(tempLine.Split() );Demimonde
sorry this works float[] temp = tempLine.Split().Select(x => float.Parse(x)).ToArray();Demimonde
D
0

Maybe could just replace "." with a ","

float amount = float.Parse("55.55".Replace(".", ","));
Duplicate answered 7/4 at 9:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.