Phoexo
Phoexo

Reputation: 2556

Converting string to float throws error "Incorrect format"

I can't get my application to convert a string into a float:

float number = float.Parse(match);

Where match is "0.791794".

Why doesn't this work? The error I get is "Input string was not in a correct format.", but I can't understand what's wrong with it.

Upvotes: 2

Views: 2753

Answers (3)

technophile
technophile

Reputation: 3676

Try passing a culture object (i.e. InvariantCulture, if this is system-stored data and the format won't ever be different) to the overload that accepts one; your current culture may be set to something that expects a comma as the separator instead of a period (or similar).

You could also try

string x = (0.791794f).ToString()

just to see what it prints out.

Checking CultureInfo.CurrentCulture might be instructive as well.

(Also, sanity check -- I assume those quotes are from you, and not part of the string value themselves?)

Upvotes: 7

Dan Blair
Dan Blair

Reputation: 2381

Seems to work fine in 2008

    static void Main(string[] args)
    {
        var match = "0.791794";
        float number = float.Parse(match);
        Console.Out.Write(number);
    }

You migth try restarting vs. Hope that helps

Upvotes: 0

Shawn Steward
Shawn Steward

Reputation: 6825

Are you sure match is a string type? You may need to typecast it.

Upvotes: 0

Related Questions