Best way to parse float?

2019-01-11 02:39发布

What is the best way to parse a float in CSharp? I know about TryParse, but what I'm particularly wondering about is dots, commas etc.

I'm having problems with my website. On my dev server, the ',' is for decimals, the '.' for separator. On the prod server though, it is the other way round. How can I best capture this?

10条回答
走好不送
2楼-- · 2019-01-11 03:18

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);
查看更多
Fickle 薄情
3楼-- · 2019-01-11 03:21

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 );
查看更多
干净又极端
4楼-- · 2019-01-11 03:22

Try to avoid float.Parse, use TryParse instead as it performs a lot better but does the same job. this also applies to double, DateTime, etc...

(some types also offer TryParseExact which also performs even better!)

查看更多
我欲成王,谁敢阻挡
5楼-- · 2019-01-11 03:31

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.

查看更多
登录 后发表回答