Best Way To Parse Float?


Answer :

I agree with leppie's reply; to put that in terms of code:

string s = "123,456.789"; float f = float.Parse(s, CultureInfo.InvariantCulture); 

Depends where the input is coming from.

If your input comes from the user, you should use the CultureInfo the user/page is using (Thread.CurrentThread.CurrentUICulture).

You can get and indication of the culture of the user, by looking at the HttpRequest.UserLanguages property. (Not correct 100%, but I've found it a very good first guess) With that information, you can set the Thread.CurrentThread.CurrentUICulture at the start of the page.

If your input comes from an internal source, you can use the InvariantCulture to parse the string.

The Parse method is somewhat easier to use, if your input is from a controlled source. That is, you have already validated the string. Parse throws a (slow) exception if its fails.

If the input is uncontrolled, (from the user, or other Internet source) the TryParse looks better to me.


If you want persist values ( numbers, date, time, etc... ) for internal purpose. Everytime use "InvariantCulture" for formating & parsing values. "InvariantCulture" is same on every computer, every OS with any user's culture/language/etc...

string strFloat = (15.789f).ToString(System.Globalization.CultureInfo.InvariantInfo); float numFloat  = float.Parse(System.Globalization.CultureInfo.InvariantInfo, strFloat); string strNow   = DateTime.Now.ToString(System.Globalization.CultureInfo.InvariantInfo); DateTime now    = DateTime.Parse(System.Globalization.CultureInfo.InvariantInfo, strNow); 

Comments

Popular posts from this blog

Are Regular VACUUM ANALYZE Still Recommended Under 9.1?

Can Feynman Diagrams Be Used To Represent Any Perturbation Theory?