2

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.

3 Answers 3

7

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

Sign up to request clarification or add additional context in comments.

5 Comments

+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.
Gah, stupid norwegian number system, we use , as decimal-seperator, and therefore it wouldn't work with the . in match.
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).
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.
You're correct, I did. I always get those two backwards. Answer revised, thanks. :)
0

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

1 Comment

match is a string, yes. I have string match = someOtherString;
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.