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:10

Pass in a CultureInfo or NumberFormatInfo that represents the culture you want to parse the float as; this controls what characters are used for decimals, group separators, etc.

For example to ensure that the '.' character was treated as the decimal indicator you could pass in CultureInfo.InvariantCulture (this one is typically very useful in server applications where you tend to want things to be the same irrespective of the environment's culture).

查看更多
你好瞎i
3楼-- · 2019-01-11 03:10

The source is an input from a website. I can't rely on it being valid. So I went with TryParse as mentioned before. But I can't figure out how to give the currentCulture to it.

Also, this would give me the culture of the server it's currently running on, but since it's the world wide web, the user can be from anywhere...

查看更多
▲ chillily
4楼-- · 2019-01-11 03:12

Since you don't know the web user's culture, you can do some guesswork. TryParse with a culture that uses , for separators and . for decimal, AND TryParse with a culture that uses . for separators and , for decimal. If they both succeed but yield different answers then you'll have to ask the user which they intended. Otherwise you can proceed normally, given your two equal results or one usable result or no usable result.

查看更多
三岁会撩人
5楼-- · 2019-01-11 03:15

you can know current Cuklture of your server with a simple statement:

System.Globalization.CultureInfo culture = System.Globalization.CultureInfo.CurrentCulture;

Note that there id a CurrentUICulture property, but UICulture is used from ResourceMeanager form multilanguages applications. for number formatting, you must considere CurrentCulture.

I hope this will help you

查看更多
劫难
6楼-- · 2019-01-11 03:16

Use a neutral culture (or one you know) when parsing with Try/Parse.

查看更多
淡お忘
7楼-- · 2019-01-11 03:17

you could always use the overload of Parse which includes the culture to use?

for instance:

Double number = Double.Parse("42,22", new CultureInfo("nl-NL").NumberFormat); // dutch number formatting

If you have control over all your data, you should use "CultureInfo.InvariantCulture" in all of your code.

查看更多
登录 后发表回答