How to use Convert.ChangeType() when conversionType is decimal and input is "40.00"

May 2024 ยท 1 minute read

I mean, I want to convert this:

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

the result is a decimal value of "4000"

the problem is that the convert call is in a very abstract generic method in a xmlToObject Converter. I don't want to add programmatically lot's of different exceptions to convert correctly.

regards Chris

2

3 Answers

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:

(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. 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); 
3

ncG1vNJzZmirpJawrLvVnqmfpJ%2Bse6S7zGiorp2jqbawutJobnBqZWV%2FcXvHqK5mrJ9iwrSxjJymp66Vp8Fur8eapaCdpK69pnnWoZynZZOku7ex0aygqKakrr2mecisZJ2dk566oriMmqWdZZmjvbbAjKKqZmxg