Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

.net - C# float.Parse String

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...