Search code examples
c#.netxsdtype-conversionmdxclient

How to convert xsd:double string to decimal in one step


I'm using MdxClient which internally parses XML documents returned by AdomdCommand.ExecuteXmlReader. Some of values are returned as xsd:double, but I want them as decimal at client side.

This library to parse values uses Convert.ChangeType method. But some of xsd:double strings such as 3.514680845402702E1 or 4.058719395866455E1 cannot been converted to decimal:

var result = Convert.ChangeType("3.514680845402702E1", typeof(decimal), CultureInfo.InvariantCulture);

throws FormatException.

I know I can convert it in two steps:

var tmp = Convert.ChangeType("3.514680845402702E1", typeof(double), CultureInfo.InvariantCulture);
var result2 = Convert.ChangeType(tmp, typeof(decimal), CultureInfo.InvariantCulture);

but I'm wondering if it's possible in one step? Maybe by providing custom IFormatProvider implementation as third argument? Any ideas?


Solution

  • Do you have to use Convert.ChangeType(...)?

    If you simply want to convert a string containing a number formatted in Exponential Notation, you can do the following:

    var result = decimal.Parse("3.514680845402702E1", System.Globalization.NumberStyles.Float);