解析浮点数的最佳方法? [英] Best way to parse float?

查看:34
本文介绍了解析浮点数的最佳方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 CSharp 中解析浮点数的最佳方法是什么?我知道 TryParse,但我特别想知道的是点、逗号等.

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?

推荐答案

取决于输入的来源.

如果您的输入来自用户,则应使用用户/页面正在使用的 CultureInfo (Thread.CurrentThread.CurrentUICulture).

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

您可以通过查看HttpRequest.UserLanguages 属性.(不是 100% 正确,但我发现这是一个很好的第一次猜测)有了这些信息,您可以设置 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.

如果您的输入来自内部来源,您可以使用 InvariantCulture 来解析字符串.

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

如果您的输入来自受控源,则 Parse 方法更易于使用.也就是说,您已经验证了字符串.如果 Parse 失败,它会抛出一个(缓慢的)异常.

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.

如果输入不受控制,(来自用户或其他 Internet 来源)TryParse 对我来说看起来更好.

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

这篇关于解析浮点数的最佳方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆