文化不变Decimal.TryParse() [英] Culture invariant Decimal.TryParse()

查看:297
本文介绍了文化不变Decimal.TryParse()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在写一个自定义字符串为十进制数字验证器需要使用Decimal.TryParse忽略文化(即如果输入含有不关心。或,作为小数点分隔符)。
这是建议的方法:

I'm writing a custom string to decimal validator that needs to use Decimal.TryParse that ignores culture (i.e. doesn't care if the input contains "." or "," as decimal point separator). This is the suggested method:

public static bool TryParse(
    string s,
    NumberStyles style,
    IFormatProvider provider,
    out decimal result
)

我想不通的第三个参数使用什么。我见过的例子是这样的:

I can't figure out what to use as the 3rd parameter. The examples I've seen look like this:

culture = CultureInfo.CreateSpecificCulture("en-GB");
Decimal.TryParse(value, style, culture, out number)



所以他们创建具体的文化。的CultureInfo不具有CreateInvariantCulture的方法,并且CultureInfo.InvariantCulture是所需类型的不。
什么是正确的用法

so they create a specific culture. CultureInfo does not have a "CreateInvariantCulture" method, and CultureInfo.InvariantCulture is not of the required type. What's the correct usage?

推荐答案

曾经尝试这样的:

decimal value;
bool b = Decimal.TryParse("0.1", NumberStyles.Any, new CultureInfo("en-US"), out value);



最好的办法很可能会使用Decimal.Parse()方法,你会传统上与任何十进制字符串值。

The best way would likely be to use the Decimal.Parse() method as you would traditionally with any decimal string values.

您可以使用NumberStyles.Currency指定的值来作为货币读取,这将照顾任何货币相关的值(你需要添加一个引用到System.Globalalization使用这样的:

You can use NumberStyles.Currency to specify that the values be read in as currency, which will take care of any currency-related values (you will need to add a Reference to System.Globalalization to use this :

using System.Globalization;

Decimal.Parse也接受第三个参数,这将让你明确地设置的IFormatProvider 如果你选择,并希望您特定的文化:

Decimal.Parse also accepts a third-parameter, which will allow you to explicitly set the IFormatProvider if you so choose and wish to you a specific Culture :

decimal value = Decimal.Parse(currency, NumberStyles.Currency, CultureInfo.InvariantCulture); //yields 15.55

这篇关于文化不变Decimal.TryParse()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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