C# 解析浮点数的最佳方法?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/147801/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Best way to parse float?
提问by Boris Callens
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.
在 CSharp 中解析浮点数的最佳方法是什么?我知道 TryParse,但我特别想知道的是点、逗号等。
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?
我的网站有问题。在我的开发服务器上,“,”代表小数,“.”代表小数。为分隔符。但是,在生产服务器上,情况正好相反。我怎样才能最好地捕捉到这一点?
采纳答案by GvS
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).
如果您的输入来自用户,则应使用用户/页面正在使用的 CultureInfo ( Thread.CurrentThread.CurrentUICulture)。
You can get and indication of the culture of the user, by looking at the HttpRequest.UserLanguagesproperty. (Not correct 100%, but I've found it a very good first guess) With that information, you can set the Thread.CurrentThread.CurrentUICultureat the start of the page.
您可以通过查看HttpRequest.UserLanguages属性来获取和指示用户的文化。(不是 100% 正确,但我发现这是一个很好的初步猜测)有了这些信息,您可以在页面的开头设置Thread.CurrentThread.CurrentUICulture。
If your input comes from an internal source, you can use the InvariantCultureto parse the string.
如果您的输入来自内部来源,您可以使用InvariantCulture来解析字符串。
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.
如果您的输入来自受控源,则 Parse 方法更易于使用。也就是说,您已经验证了该字符串。如果 Parse 失败,它会抛出一个(慢)异常。
If the input is uncontrolled, (from the user, or other Internet source) the TryParselooks better to me.
如果输入不受控制(来自用户或其他 Internet 来源),TryParse对我来说看起来更好。
回答by leppie
Use a neutral culture (or one you know) when parsing with Try/Parse.
使用 Try/Parse 解析时使用中性文化(或您知道的文化)。
回答by TcKs
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...
如果您希望为内部目的保留值(数字、日期、时间等)。每次都使用“InvariantCulture”来格式化和解析值。“InvariantCulture”在每台计算机、具有任何用户文化/语言/等的每个操作系统上都是相同的......
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);
回答by Greg Beech
Pass in a CultureInfoor NumberFormatInfothat represents the culture you want to parse the float as; this controls what characters are used for decimals, group separators, etc.
传入一个CultureInfo或NumberFormatInfo来表示你想将浮点解析为的文化;这控制用于小数、组分隔符等的字符。
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).
例如确保'.' 字符被视为您可以在 CultureInfo.InvariantCulture 中传递的十进制指示符(这在服务器应用程序中通常非常有用,在这些应用程序中您往往希望无论环境的文化如何都相同)。
回答by Marc Gravell
I agree with leppie's reply; to put that in terms of code:
我同意 leppie 的回复;把它放在代码方面:
string s = "123,456.789";
float f = float.Parse(s, CultureInfo.InvariantCulture);
回答by Davy Landman
You could always use the overload of Parsewhich includes the culture to use?
你总是可以使用Parse的重载,其中包括要使用的文化?
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.
如果您可以控制所有数据,则应在所有代码中使用“CultureInfo.InvariantCulture”。
回答by Joachim Kerschbaumer
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...
尽量避免 float.Parse,改用 TryParse,因为它的性能要好得多,但也做同样的工作。这也适用于 double、DateTime 等...
(some types also offer TryParseExact which also performs even better!)
(某些类型还提供 TryParseExact,它的性能甚至更好!)
回答by Boris Callens
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.
源是来自网站的输入。我不能指望它是有效的。所以我选择了之前提到的 TryParse。但我不知道如何将 currentCulture 赋予它。
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...
此外,这会给我它当前运行的服务器的文化,但由于它是万维网,用户可以来自任何地方......
回答by Windows programmer
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.
由于您不了解网络用户的文化,因此您可以进行一些猜测。TryParse 的区域性使用 , 作为分隔符和 . 用于十进制,并且 TryParse 具有使用 . 分隔符和 , 小数点。如果他们都成功但产生了不同的答案,那么您将不得不询问用户他们的意图。否则,您可以正常进行,因为您的两个结果相同,或者一个可用的结果或没有可用的结果。
回答by stefano m
you can know current Cuklture of your server with a simple statement:
您可以使用简单的语句了解服务器的当前 Cuklture:
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.
请注意,有一个 CurrentUICulture 属性,但 UICulture 是从 ResourceMeanager 表单多语言应用程序中使用的。对于数字格式,您必须考虑 CurrentCulture。
I hope this will help you
我希望这能帮到您