views:

195

answers:

3

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.

A: 

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

Shawn Steward
`match` is a `string`, yes. I have `string match = someOtherString;`
Phoexo
+7  A: 

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

technophile
+1 I haven't run into this yet, and I don't know why I haven't given the number of documents we run through. But this is really a good point.
Dan Blair
Gah, stupid norwegian number system, we use `,` as decimal-seperator, and therefore it wouldn't work with the `.` in `match`.
Phoexo
Yeah. Invalid format means it didn't match the rules the current UI culture expects, which for numbers usually means comma-vs-period IME. ;) Anytime you call .ToString, string.Format, or .Parse you should pass some kind of CultureInfo object, just to make it explicit what the possibilities are (and make you consider different culture rules).
technophile
@technophile: I think you meant to refer to the `CurrentCulture` property, not `CurrentUICulture`. `CurrentUICulture` is related to how a resource manager loads resources (such as strings from resource files). `CurrentCulture` affects date- and number formats.
Fredrik Mörk
You're correct, I did. I always get those two backwards. Answer revised, thanks. :)
technophile
A: 

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

Dan Blair