0

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?

tom redfern
  • 30,562
  • 14
  • 91
  • 126
Piotr Sobiegraj
  • 1,775
  • 16
  • 26
  • What's wrong with parsing it as `double`, then casting to `decimal`? If you can change the invocation to `Convert.ChangeType()`, then surely you can stick a cast in front of it as well, or am I missing something obvious? Writing a custom `FormatProvider` just so you can coax `Convert.ChangeType()` into doing it for you seems rather roundabout. – Jeroen Mostert Feb 19 '15 at 15:49
  • @JeroenMostert method AdjustValueFromColumnType from https://github.com/DynamicTyped/MdxClient/blob/master/MdxClient/MdxCommand.cs is used to convert many types. I've changed it to sth similar to if (IsDecimalFixNeeded(resultSetType, cellType)) {FirstConvert();} Convert(); but I think that one convert will be more elegant solution. – Piotr Sobiegraj Feb 19 '15 at 16:25

1 Answers1

2

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);
Yannick Meeus
  • 5,643
  • 1
  • 35
  • 34