简体   繁体   English

当conversionType为十进制且输入为“40.00”时,如何使用Convert.ChangeType()

[英]How to use Convert.ChangeType() when conversionType is decimal and input is “40.00”

I mean, I want to convert this: 我的意思是,我想转换这个:

string a = "40.00";
Convert.ChangeType(a, typeof(decimal))

the result is a decimal value of "4000" 结果是十进制值“4000”

the problem is that the convert call is in a very abstract generic method in a xmlToObject Converter. 问题是转换调用是在xmlToObject转换器中的一个非常抽象的泛型方法。 I don't want to add programmatically lot's of different exceptions to convert correctly. 我不想以编程方式添加许多不同的异常来正确转换。

regards Chris 对克里斯说

The decimal point might not be represented by the period character in your current culture. 您当前文化中的句点字符可能不会表示小数点。

In general, when performing culture-invariant conversions, it's best to specify CultureInfo.InvariantCulture as the IFormatProvider argument to the method : 在一般情况下,进行区域性不变的转换时,最好到指定CultureInfo.InvariantCulture作为IFormatProvider参数的方法

(decimal) Convert.ChangeType(a, typeof(decimal), CultureInfo.InvariantCulture);

The conversion is most likely done using a culture that uses the period as thousands separator instead of decimal separator. 转换很可能是使用将句点用作千位分隔符而不是小数分隔符的文化来完成的。

Specify the culture when you convert the value: 转换值时指定区域性:

Convert.ToDecimal(a, CultureInfo.InvariantCulture)

The following code 以下代码

 string s = "40.00";
 decimal d = (decimal)Convert.ChangeType(s, typeof(decimal));

makes d = 40. This looks fine for me. 使d = 40.这对我来说很好。 What is your issue exactly? 你到底是什么问题?

Edit: It seems you might have an issue with the culture used. 编辑:似乎您可能对使用的文化有问题。 Do this for conversion: 这样做是为了转换:

string s = "40.00";
decimal d = (decimal)Convert.ChangeType(s, typeof(decimal), CultureInfo.InvariantCulture);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM