Piotr Sobiegraj
Piotr Sobiegraj

Reputation: 1783

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?

Upvotes: 0

Views: 747

Answers (1)

Yannick Meeus
Yannick Meeus

Reputation: 5910

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);

Upvotes: 2

Related Questions